package com.jwsoft.manager.core.integration.individuation.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.common.vo.dict.DictQueryVO;
import com.bifang.module.base.common.vo.dict.DictVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.system.common.enums.CardTypeEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.enums.SourceTypeEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheVO;
import com.jwsoft.manager.common.vo.dygx.CszmQueryVO;
import com.jwsoft.manager.common.vo.dygx.DyJzzVO;
import com.jwsoft.manager.common.vo.dygx.WqVO;
import com.jwsoft.manager.common.vo.eduCompany.EduCompanyVO;
import com.jwsoft.manager.common.vo.eduHouse.EduHouseHoldInterfaceVO;
import com.jwsoft.manager.common.vo.eduHouse.EduHouseVO;
import com.jwsoft.manager.common.vo.eduHouse.HouseInterfaceDetailVO;
import com.jwsoft.manager.common.vo.eduHouse.HouseInterfaceVO;
import com.jwsoft.manager.common.vo.eduHouseDetail.EduHouseDetailVO;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdVO;
import com.jwsoft.manager.common.vo.eduJhjyQuerySync.JhjyQueryVO;
import com.jwsoft.manager.common.vo.eduJhjySync.*;
import com.jwsoft.manager.common.vo.eduLivePlace.EduLivePlaceVO;
import com.jwsoft.manager.common.vo.eduNetsign.EduNetsignVO;
import com.jwsoft.manager.common.vo.eduSocialSecurity.EduSocialSecurityVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.SaveStudentEnrollVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.StudentFormVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollBefore.BatchCreateVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollPre.EduStudentEnrollPreKeyVO;
import com.jwsoft.manager.common.vo.individuation.*;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduSyncIrsIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.integration.common.JhIrsIntegration;
import com.jwsoft.manager.core.integration.individuation.IndividuationIntegration;
import com.jwsoft.manager.core.integration.individuation.helper.DyEnrollCalculateCreateHelper;
import com.jwsoft.manager.core.integration.individuation.helper.JhEnrollBeforeCreateHelper;
import com.jwsoft.manager.core.integration.individuation.helper.JhEnrollHelper;
import com.jwsoft.manager.core.integration.individuation.helper.JhImitateEnrollHelper;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 金华个性化接口
 * @Author zhiyuan
 * @Date 2023/12/27 9:37
 */
@Service
@ApiService(funcCode = "F330700", title = "金华个性化接口")
public class JhIndividuationIntegrationImpl implements IndividuationIntegration {
    @Autowired
    JhEnrollBeforeCreateHelper jhEnrollBeforeCreateHelper;
    @Autowired
    public JhIrsIntegration jhIrsIntegration;
    @Autowired
    public OperationCacheIntegration operationCacheIntegration;
    @Autowired
    public EduHouseholdService eduHouseholdService;

    @Autowired
    public EduAddressService eduAddressService;

    @Autowired
    public EduHouseDetailService eduHouseDetailService;

    @Autowired
    public CommonIntegration commonIntegration;

    @Autowired
    public EduHouseService eduHouseService;

    @Autowired
    public DictIntegration dictIntegration;

    @Autowired
    public EduNetsignService eduNetsignService;

    @Autowired
    public EduSocialSecurityService eduSocialSecurityService;

    @Autowired
    public EduCompanyService eduCompanyService;

    @Autowired
    public EduLivePlaceService eduLivePlaceService;

    @Autowired
    private EduAuthSchoolService eduAuthSchoolService;
    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;
    @Autowired
    private DyEnrollCalculateCreateHelper dyEnrollCalculateCreateHelper;
    @Autowired
    private JhEnrollHelper jhEnrollHelper;
    @Autowired
    private JhImitateEnrollHelper jhImitateEnrollHelper;
    @Autowired
    private EduSocialSecurityDetailService eduSocialSecurityDetailService;
    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private EduHouseDetailNurseryService eduHouseDetailNurseryService;
    @Autowired
    private EduHouseNurseryService eduHouseNurseryService;
    @Autowired
    private EduHouseholdGaService eduHouseholdGaService;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    private final String areaCode = "330700";
    private final boolean cszFlag=false;//是否比对出生证信息

    @Override
    @OpApi(funcCode = "F3307000001", title = "金华户籍接口信息获取并保存", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduHouseholdVO> saveHouseHoldData(HouseHoldSaveVO vo) {
        List<EduHouseholdVO> eduHouseholdVOList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getIdcard())) {
            return null;
        }
        if(vo.getLocalFlag()==null){
            vo.setLocalFlag(false);
        }
        String bnxxFlag="1";
        String bnczFlag="1";
        if(StringUtils.isNotBlank(vo.getStudentEnrollPreId())){
            bnxxFlag="0";
            bnczFlag="0";
            EduStudentEnrollPre eduStudentEnrollPre=eduStudentEnrollPreService.getById(vo.getStudentEnrollPreId());
            if(eduStudentEnrollPre!=null){
                if(SchoolCategoryEnum.PRIMARY.getType().equals(eduStudentEnrollPre.getSchoolCategory())){
                    bnxxFlag="1";
                }
                if(SchoolCategoryEnum.JUNIOR.getType().equals(eduStudentEnrollPre.getSchoolCategory())){
                    bnczFlag="1";
                }
            }
        }
        vo.setBnczFlag(bnczFlag);
        vo.setBnxxFlag(bnxxFlag);
        try {
            int year = operationCacheIntegration.getPeriodYear().getYear();

            //同步调用，服务器网络和irs省网络联通条件下可直接调用
            JSONArray jsonArray = jhIrsIntegration.getFamilyInfoIrs(vo.getIdcard(),vo.getReqIp());
            if (jsonArray != null && jsonArray.size() > 0) {
                jsonArray.forEach(
                        item -> {
                            JSONObject personData = (JSONObject) item;
                            EduHouseHoldInterfaceVO holdInterfaceVO =
                                    personData
                                            .getJSONObject("ELC_LICENCE_STRUCT")
                                            .getObject("DATA", EduHouseHoldInterfaceVO.class);
                            String elcLicenceName = (String) personData.get("ELC_LICENCE_NAME");
                            holdInterfaceVO.setElcLicenceName(elcLicenceName);
                            QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
                            householdQueryWrapper
                                    .lambda().select(EduHousehold::getHouseholdId,EduHousehold::getAddress)
                                    .eq(EduHousehold::getYear, year)
                                    .eq(EduHousehold::getIdcard, holdInterfaceVO.getCZRKGMSFHM());
                            List<EduHousehold> oldList =
                                    eduHouseholdService.list(householdQueryWrapper);
                            EduHousehold eduHousehold = new EduHousehold();
                            String oldAddress="";
                            if (!CollectionUtils.isEmpty(oldList)) {
                                eduHousehold.setHouseholdId(oldList.get(0).getHouseholdId());
                                oldAddress=oldList.get(0).getAddress();
                                eduHousehold.setQysj(oldList.get(0).getQysj());
                                eduHousehold.setHsqlbz(oldList.get(0).getHsqlbz());
                                eduHousehold.setHsqlbs(oldList.get(0).getHsqlbs());
                            }else{
                                eduHousehold.setHouseholdId(IdUtil.simpleUUID());
                            }

                            eduHousehold.setHhid(holdInterfaceVO.getCZRKHHID());
                            eduHousehold.setHh(holdInterfaceVO.getCZRKHH());
                            eduHousehold.setIdcard(holdInterfaceVO.getCZRKGMSFHM());
                            eduHousehold.setFullName(holdInterfaceVO.getCZRKXM());
                            eduHousehold.setAddress(holdInterfaceVO.getCZRKZZ());
                            eduHousehold.setBirthday(holdInterfaceVO.getCZRKCSRQ());
                            eduHousehold.setSex(holdInterfaceVO.getCZRKXB());
                            eduHousehold.setCountry(holdInterfaceVO.getCZRKJGGJ());
                            eduHousehold.setBirthplace(holdInterfaceVO.getCZRKCSDSSX());
                            eduHousehold.setNativePlace(holdInterfaceVO.getCZRKJGSSX());
                            eduHousehold.setHouseholdPlace(holdInterfaceVO.getCZRKZZ());
                            eduHousehold.setAccountType(holdInterfaceVO.getElcLicenceName());
                            eduHousehold.setRelation(holdInterfaceVO.getCZRKYHZGX());
                            eduHousehold.setHouseholder(holdInterfaceVO.getCZRKHZXM());
                            eduHousehold.setServiceSpaces(holdInterfaceVO.getCZRKFWCS());
                            eduHousehold.setHssqlbz(holdInterfaceVO.getCZRKHZQLSSX());
                            eduHousehold.setHssqxqlws(holdInterfaceVO.getCZRKHDQLXZ());
                            eduHousehold.setHxzlbd(holdInterfaceVO.getCZRKHZQLXZ());

                            if(StringUtils.isNotBlank(holdInterfaceVO.getCZRKHSQLBS())) {
                                eduHousehold.setHsqlbs(holdInterfaceVO.getCZRKHSQLBS());
                            }

                            if (StringUtils.isNotBlank(holdInterfaceVO.getCZRKHSQLBZ())) {
                                eduHousehold.setHsqlbz(holdInterfaceVO.getCZRKHSQLBZ());
                                eduHousehold.setQysj(holdInterfaceVO.getCZRKHSQLBZ());
                                try {
                                    if (holdInterfaceVO.getCZRKHSQLBZ().length() == 8) {
                                        eduHousehold.setRegistrationDate(DatePattern.PURE_DATE_FORMAT.parse(holdInterfaceVO.getCZRKHSQLBZ()));
                                    } else if (holdInterfaceVO.getCZRKHSQLBZ().length() == 10) {
                                        eduHousehold.setRegistrationDate(DatePattern.NORM_DATE_FORMAT.parse(holdInterfaceVO.getCZRKHSQLBZ()));
                                    }
                                } catch (Exception e) {
                                    logger.error("户籍迁入时间格式转换异常");
                                }

                            }
                            eduHousehold.setAuthStatus(AuthStatusEnum.YES.getType());
                            eduHousehold.setStatus(BoolEnum.TRUE.getType());
                            String yearString = Integer.toString(year);
                            eduHousehold.setYear(yearString);
                            String addressId =
                                    eduAddressService.saveByAddress(eduHousehold.getAddress(),Integer.parseInt(eduHousehold.getYear()),vo.getBnxxFlag(),vo.getBnczFlag());
                            eduHousehold.setAddressId(addressId);
                            if (StringUtils.isNotBlank(eduHousehold.getAddress())){
                                if(eduHousehold.getAddress().indexOf("金华")>=0){
                                    eduHousehold.setAreaCode("330700");
                                    if(eduHousehold.getAddress().indexOf("金东区")>=0){
                                        eduHousehold.setAreaCode("330703");
                                    }
                                    if(eduHousehold.getAddress().indexOf("婺城区")>=0){
                                        eduHousehold.setAreaCode("330702");
                                    }
                                    if(eduHousehold.getAddress().indexOf("开发区")>=0){
                                        eduHousehold.setAreaCode("330704");
                                    }
                                }
                                if (StringUtils.isNotBlank(eduHousehold.getRegistrationAuthority())){
                                    if(eduHousehold.getRegistrationAuthority().indexOf("金东")>=0){
                                        eduHousehold.setAreaCode("330703");
                                    }
                                    if(eduHousehold.getRegistrationAuthority().indexOf("婺城")>=0){
                                        eduHousehold.setAreaCode("330702");
                                    }
                                    if(eduHousehold.getRegistrationAuthority().indexOf("江南")>=0){
                                        eduHousehold.setAreaCode("330704");
                                    }
                                }
                            }
                            if(StringUtils.isBlank(eduHousehold.getQysj())&&vo.getIdcard().equalsIgnoreCase(eduHousehold.getIdcard())){
                                //去金华公安导入库中查询
                                LambdaQueryWrapper<EduHouseholdGa> lambdaQueryWrapper=new LambdaQueryWrapper<>();
                                lambdaQueryWrapper.eq(EduHouseholdGa::getIdcard,vo.getIdcard()).eq(EduHouseholdGa::getYear,year)
                                        .eq(EduHouseholdGa::getHh,eduHousehold.getHh());
                                EduHouseholdGa eduHouseholdGa=eduHouseholdGaService.getOne(lambdaQueryWrapper,false);
                                if(eduHouseholdGa!=null){

                                    eduHousehold.setHsqlbs(eduHouseholdGa.getHsqlbs());
                                    eduHousehold.setHsqlbz(eduHouseholdGa.getHsqlbz());
                                    if(StringUtils.isNotBlank(eduHouseholdGa.getHsqlbz())){
                                        eduHousehold.setQysj(eduHouseholdGa.getHsqlbz());
                                    }else{
                                        eduHousehold.setQysj(eduHouseholdGa.getHsqlbs());
                                    }
                                    if(StringUtils.isNotBlank(eduHousehold.getQysj())){
                                        try {
                                            if (eduHousehold.getQysj().length() == 8) {
                                                eduHousehold.setRegistrationDate(DatePattern.PURE_DATE_FORMAT.parse(eduHousehold.getQysj()));
                                            } else if (eduHouseholdGa.getHsqlbz().length() == 10) {
                                                eduHousehold.setRegistrationDate(DatePattern.NORM_DATE_FORMAT.parse(eduHousehold.getQysj()));
                                            }
                                        } catch (Exception e) {
                                            logger.error("户籍迁入时间格式转换异常");
                                        }
                                    }

                                }
                                //地址有变化才去更新
                                eduHouseholdService.saveOrUpdate(eduHousehold);

                            }else{
                                if (!eduHousehold.getAddress().equalsIgnoreCase(oldAddress)) {
                                    //地址有变化才去更新
                                    eduHouseholdService.saveOrUpdate(eduHousehold);
                                }
                            }

                            eduHouseholdVOList.add(Convert.convert(EduHouseholdVO.class, eduHousehold));
                        });
            } else {
                QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
                householdQueryWrapper
                        .lambda().select(EduHousehold::getHouseholdId)
                        .eq(EduHousehold::getIdcard, vo.getIdcard())
                        .eq(EduHousehold::getYear, year);
                List<EduHousehold> oldList =
                        eduHouseholdService.list(householdQueryWrapper);
                if (!CollectionUtils.isEmpty(oldList)) {
                    List<String> idList = oldList.stream()
                            .map(EduHousehold::getHouseholdId)
                            .collect(Collectors.toList());
                    eduHouseholdService.removeByIds(idList);
                }
            }

        } catch(AppException e){
            throw e;
        } catch(Exception e){
            throw new AppException(e.getMessage());
        }

        return eduHouseholdVOList;
    }

    @Override
    @OpApi(funcCode = "F3307000002", title = "金华房产接口信息获取并保存", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduHouseVO> saveHouseInterfaceData(HouseInterfaceSaveVO vo) {
        String bnxxFlag="1";
        String bnczFlag="1";
        if(StringUtils.isNotBlank(vo.getStudentEnrollPreId())){
            bnxxFlag="0";
            bnczFlag="0";
            EduStudentEnrollPre eduStudentEnrollPre=eduStudentEnrollPreService.getById(vo.getStudentEnrollPreId());
            if(eduStudentEnrollPre!=null){
                if(SchoolCategoryEnum.PRIMARY.getType().equals(eduStudentEnrollPre.getSchoolCategory())){
                    bnxxFlag="1";
                }
                if(SchoolCategoryEnum.JUNIOR.getType().equals(eduStudentEnrollPre.getSchoolCategory())){
                    bnczFlag="1";
                }
            }
        }
        vo.setBnczFlag(bnczFlag);
        vo.setBnxxFlag(bnxxFlag);
        List<EduHouseVO> eduHouseVOList = new ArrayList<>();
        try {
            int year = operationCacheIntegration.getPeriodYear().getYear();
            QueryWrapper<EduHouseDetail> oldDetailQueryWrapper = new QueryWrapper<>();
            oldDetailQueryWrapper
                    .lambda()
                    .in(EduHouseDetail::getIdcard, vo.getAllIdcardList())
                    .eq(EduHouseDetail::getYear, year)
                    .select(EduHouseDetail::getHouseId);
            List<EduHouseDetail> detailListOld = eduHouseDetailService.list(oldDetailQueryWrapper);
            List<String> houseIdList = new ArrayList<>();

            Map<String, List<EduHouseDetail>> oldGroupBy = new HashMap<>();
            if (!CollectionUtils.isEmpty(detailListOld)) {
                houseIdList = detailListOld.stream().map(EduHouseDetail::getHouseId).distinct().collect(Collectors.toList());
                QueryWrapper<EduHouseDetail> detailQueryWrapper = new QueryWrapper<>();
                detailQueryWrapper.lambda().in(EduHouseDetail::getHouseId, houseIdList);
                List<EduHouseDetail> oldDetailList = eduHouseDetailService.list(detailQueryWrapper);
                if (!CollectionUtils.isEmpty(oldDetailList)) {
                    oldGroupBy = oldDetailList.stream().collect(Collectors.groupingBy(EduHouseDetail::getHouseId));
                }
            }
            //地址过滤
            CommonVO commonVO = new CommonVO();
            commonVO.setAreaCode(areaCode);
            commonVO.setParamKey("house_address_gl_key");
            String glHouseAddress = commonIntegration.getValueByKeyAndArea(commonVO);
            List<String> glAddressList = StringUtils.isNotBlank(glHouseAddress) ? Arrays.stream(glHouseAddress.split(",")).map(s -> s).collect(Collectors.toList()) : new ArrayList<>();
            CommonVO commonFcLxVO = new CommonVO();
            commonFcLxVO.setAreaCode(areaCode);
            commonFcLxVO.setParamKey("edu_house_type_filterate");
            String fclx = commonIntegration.getValueByKeyAndArea(commonFcLxVO);
            List<String> fclxList = StringUtils.isNotBlank(fclx) ? Arrays.stream(fclx.split(",")).map(s -> s).collect(Collectors.toList()) : new ArrayList<>();

            final Map<String, List<EduHouseDetail>> oldGroupByFinal = oldGroupBy;
            JSONArray houseArr = new JSONArray();
            if (StringUtils.isNotBlank(vo.getIdcard())) {
                JSONArray houseStArr = jhIrsIntegration.getFcJh(vo.getName(), vo.getIdcard(),vo.getReqIp());
                if (houseStArr != null) {
                    houseArr.addAll(houseStArr);
                }
                if (vo.getIdcard().indexOf("X") > 0) {
                    JSONArray houseStArrX = jhIrsIntegration.getFcJh(vo.getName(), vo.getIdcard().toLowerCase(),vo.getReqIp());
                    if (houseStArrX != null) {
                        houseArr.addAll(houseStArrX);
                    }
                }
            }

            if (StringUtils.isNotBlank(vo.getFatherIdcard())) {
                JSONArray houseFaArr = jhIrsIntegration.getFcJh(vo.getFatherName(), vo.getFatherIdcard(),vo.getReqIp());
                if (houseFaArr != null) {
                    houseArr.addAll(houseFaArr);
                }
                if (vo.getFatherIdcard().indexOf("X") > 0) {
                    JSONArray houseFaArrX = jhIrsIntegration.getFcJh(vo.getFatherName(), vo.getFatherIdcard().toLowerCase(),vo.getReqIp());
                    if (houseFaArrX != null) {
                        houseArr.addAll(houseFaArrX);
                    }
                }
            }
            if (StringUtils.isNotBlank(vo.getMotherIdcard())) {
                JSONArray houseMoArr = jhIrsIntegration.getFcJh(vo.getMotherName(), vo.getMotherIdcard(),vo.getReqIp());
                if (houseMoArr != null) {
                    houseArr.addAll(houseMoArr);
                }
                if (vo.getMotherIdcard().indexOf("X") > 0) {
                    JSONArray houseMoArrX = jhIrsIntegration.getFcJh(vo.getMotherName(), vo.getMotherIdcard().toLowerCase(),vo.getReqIp());
                    if (houseMoArrX != null) {
                        houseArr.addAll(houseMoArrX);
                    }
                }
            }
            List<String> oldHouseIdList = new ArrayList<>();
            if (houseArr.size() > 0) {
                int finalYear = year;
                List<Map<String, String>> hasList = new ArrayList<>();
                List<String> hasBdcdyhList = new ArrayList<>();
                for (Object item : houseArr) {
                    HouseInterfaceVO house = Convert.convert(HouseInterfaceVO.class, item);
                    String realProperty = house.getQlrxxList().stream()
                            .map(HouseInterfaceDetailVO::getBdcqzh)
                            .distinct()
                            .collect(Collectors.joining(","));

                    if (!ObjectUtils.isEmpty(house.getBdcdyh())) {
                        if (hasBdcdyhList.contains(house.getBdcdyh())) {
                            continue;
                        }
                        hasBdcdyhList.add(house.getBdcdyh());
                    } else {
                        Map<String, String> realMap = new HashMap<>();
                        realMap.put("realProperty", realProperty);
                        realMap.put("zl", house.getZl());
                        boolean continueFlg = false;
                        for (Map<String, String> map : hasList) {
                            if (map.get("realProperty").equals(realProperty) && map.get("zl").equals(house.getZl())) {
                                continueFlg = true;
                                break;
                            }
                        }
                        if (continueFlg) {
                            continue;
                        }
                        hasList.add(realMap);
                    }

                    QueryWrapper<EduHouse> houseQueryWrapper = new QueryWrapper<>();
                    List<String> qlrList = new ArrayList<>();
                    List<String> qlrAllList = new ArrayList<>();
                    String qlrName = "";
                    boolean idcardFlag = true;
                    List<String> qlrNameList = new ArrayList<>();
                    Double qlbl=0.0;
                    Integer qlrCnt=house.getQlrxxList().size();
                    for (HouseInterfaceDetailVO detailVO : house.getQlrxxList()) {
                        if (StringUtils.isBlank(detailVO.getZjh())) {
                            idcardFlag = false;
                        } else {

                            if (IdcardUtil.isValidCard(detailVO.getZjh())) {
                                idcardFlag = false;
                                qlrAllList.add(detailVO.getZjh().toUpperCase());
                            } else {
                                if (detailVO.getZjh().length() == 15) {
                                    qlrList.add(IdcardUtil.convert15To18(detailVO.getZjh().toUpperCase()));
                                    qlrAllList.add(IdcardUtil.convert15To18(detailVO.getZjh().toUpperCase()));
                                } else {
                                    qlrList.add(detailVO.getZjh().toUpperCase());
                                    qlrAllList.add(detailVO.getZjh().toUpperCase());
                                }
                            }

                        }
                        qlrNameList.add(detailVO.getQlr().trim());
                        if (StringUtils.isBlank(qlrName)) {
                            if(StringUtils.isNotBlank(detailVO.getQlbl())){
                                qlrName = detailVO.getQlr() + "(" + detailVO.getZjh() + "占比:"+detailVO.getQlbl()+")";
                            }else{
                                qlrName = detailVO.getQlr() + "(" + detailVO.getZjh() + "占比:"+(Math.round(10000/qlrCnt) / 100.0)+"%)";
                            }

                        } else {
                            if(StringUtils.isNotBlank(detailVO.getQlbl())){
                                qlrName = qlrName + "," +detailVO.getQlr() + "(" + detailVO.getZjh() + "占比:"+detailVO.getQlbl()+")";
                            }else {
                                qlrName = qlrName + "," + detailVO.getQlr() + "(" + detailVO.getZjh()  + "占比:"+(Math.round(10000/qlrCnt) / 100.0)+"%)";
                            }
                        }
                        if(StringUtils.isNotBlank(detailVO.getQlbl())){
                            try {
                                if (StringUtils.isNotBlank(detailVO.getZjh()) && vo.getAllIdcardList().contains(detailVO.getZjh().toUpperCase())) {
                                    qlbl = qlbl + Double.parseDouble(Convert.toDBC(detailVO.getQlbl()).replaceAll("%", ""));
                                }
                                if (StringUtils.isNotBlank(detailVO.getQlr()) && vo.getAllIdcardList().contains(detailVO.getQlr())) {
                                    qlbl = qlbl + Double.parseDouble(Convert.toDBC(detailVO.getQlbl()).replaceAll("%", ""));
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }else{
                            if (StringUtils.isNotBlank(detailVO.getZjh()) && vo.getAllIdcardList().contains(detailVO.getZjh().toUpperCase())) {
                                qlbl=qlbl+ Math.round(10000/qlrCnt) / 100.0;
                            }
                            if (StringUtils.isNotBlank(detailVO.getQlr()) && vo.getAllIdcardList().contains(detailVO.getQlr())) {
                                qlbl=qlbl+Math.round(10000/qlrCnt) / 100.0;
                            }

                        }

                    }
                    EduHouse odlHouse = null;
                    if (ObjectUtils.isEmpty(house.getBdcdyh())) {
                        //不动单元号为空，使用不动产权号和证件类型查询
                        QueryWrapper<EduHouseDetail> houseDetailQueryWrapper =
                                new QueryWrapper<>();
                        houseDetailQueryWrapper
                                .lambda()
                                .eq(EduHouseDetail::getYear, finalYear)

                                .in(
                                        EduHouseDetail::getRealProperty,
                                        house.getQlrxxList().stream()
                                                .map(HouseInterfaceDetailVO::getBdcqzh)
                                                .collect(Collectors.toList()))
                                .in(
                                        EduHouseDetail::getIdcard,
                                        qlrAllList)
                                .select(EduHouseDetail::getHouseId);
                        List<EduHouseDetail> detailList = eduHouseDetailService.list(houseDetailQueryWrapper);
                        if (!CollectionUtils.isEmpty(detailList)) {
                            List<String> idList =
                                    detailList.stream()
                                            .map(EduHouseDetail::getHouseId)
                                            .distinct()
                                            .collect(Collectors.toList());
                            for (int i = 0; i < idList.size(); i++) {
                                EduHouse oldhouseById = eduHouseService.getById(idList.get(i));
                                if (oldhouseById != null && house.getZl().equals(oldhouseById.getAddress())) {
                                    odlHouse = oldhouseById;
                                }
                            }
                        }

                    } else {
                        houseQueryWrapper
                                .lambda()
                                .eq(EduHouse::getRealPropertyNum, house.getBdcdyh())
                                .eq(EduHouse::getRealProperty, realProperty)
                                .eq(EduHouse::getYear, finalYear);
                        odlHouse = eduHouseService.getOne(houseQueryWrapper);
                    }
                    String authStatus = null;
                    String status = null;
                    EduHouse eduHouse;
                    boolean newFlag = false;
                    boolean statusFlag = false;
                    if (!ObjectUtils.isEmpty(odlHouse)) {
                        if (oldHouseIdList.contains(odlHouse.getHouseId())) {
                            continue;
                        }
                        eduHouse = odlHouse;
                        oldHouseIdList.add(odlHouse.getHouseId());
                        statusFlag = false;//金华重新获取的时候全部重新核验
                        if(StringUtils.isNotBlank(odlHouse.getRemark())){
                            if(odlHouse.getRemark().indexOf("人工核验")>=0){
                                statusFlag=true;
                            }
                        }
                        if(statusFlag){
                            authStatus = odlHouse.getAuthStatus();//获取老数据的审核状态
                            status = odlHouse.getStatus();//获取老数据的有效状态
                        }

                        newFlag = false;
                    } else {
                        eduHouse = new EduHouse();
                        eduHouse.setHouseId(IdUtil.simpleUUID());
                        newFlag = true;
                    }
                    eduHouse.setAddress(house.getZl());
                    if (!ObjectUtils.isEmpty(house.getDjsj())) {
                        eduHouse.setRegisterDate(
                                DateUtil.parse(house.getDjsj(), "yyyy年MM月dd日"));
                    }
                    if (!ObjectUtils.isEmpty(house.getQlrxxList())) {
                        eduHouse.setRealProperty(realProperty);
                    }
                    eduHouse.setRealPropertyNum(house.getBdcdyh());
                    if (!ObjectUtils.isEmpty(house.getTdsyqssj())) {
                        eduHouse.setBegDate(
                                DateUtil.parse(house.getTdsyqssj(), "yyyy年MM月dd日"));
                    }
                    if (!ObjectUtils.isEmpty(house.getTdsyjssj())) {
                        eduHouse.setEndDate(
                                DateUtil.parse(house.getTdsyjssj(), "yyyy年MM月dd日"));
                    }
                    String yt = house.getYt().replace("/", "").trim();
                    eduHouse.setLandCategories(
                            saveDict("LANDCATEGORIES", yt, vo.getAccessToken()));
                    eduHouse.setLandCategoriesName(yt);
                    eduHouse.setHouseNature(
                            saveDict("HOUSENATURE", house.getFwxz(), vo.getAccessToken()));
                    eduHouse.setHouseNatureName(house.getFwxz());
                    eduHouse.setYear(finalYear);
                    eduHouse.setStatus("1");
                    eduHouse.setAuthStatus(AuthStatusEnum.NODO.getType());
                    qlbl=Math.round(qlbl*100) / 100.0;
                    eduHouse.setPrimarySchoolOne(qlbl.toString()+"%");
                    ArrayList<EduHouseDetail> detailList = new ArrayList<>();
                    if (!ObjectUtils.isEmpty(house.getQlrxxList())) {
                        List<HouseInterfaceDetailVO> qlrxxList = house.getQlrxxList();
                        eduHouse.setQlrNum(qlrxxList.size());

                        eduHouse.setQlrName(qlrName);
                        if (qlrxxList.size() >= 3) {
                            //大于等于3个权利人的，设置为待审核
                            if(qlbl<=0){
                                eduHouse.setAuthStatus(AuthStatusEnum.NODO.getType());
                                eduHouse.setStatus(BoolEnum.TRUE.getType());
                                if (!statusFlag) {
                                    eduHouse.setRemark("系统判断权利人大于3个,不动产未返回占有比例，需要人工核验份额");
                                }
                            }else{
                                if(qlbl>=50){
                                    eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                                    eduHouse.setStatus(BoolEnum.TRUE.getType());
                                    if (!statusFlag) {
                                        eduHouse.setRemark("系统判断权利人大于3个且分额大于等于51%，设置为有效");
                                    }
                                }else{
                                    eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                                    eduHouse.setStatus(BoolEnum.FALSE.getType());
                                    if (!statusFlag) {
                                        eduHouse.setRemark("系统判断权利人大于3个且分额不足50%，设置为无效");
                                    }
                                }
                            }

                        } else if (qlrxxList.size() == 1) {
                            //1个权利人的直接通过
                            eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                            eduHouse.setStatus(BoolEnum.TRUE.getType());
                            eduHouse.setPrimarySchoolOne("100%");
                        } else if (qlrxxList.size() == 2) {
                            //2个权利人的，如果是父母双方，则直接有效，不然就是无效
                            if (!CollectionUtils.isEmpty(qlrList)) {
                                if (idcardFlag) {

                                    if (vo.getAllIdcardList()
                                            .containsAll(qlrList)) {
                                        eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                                        eduHouse.setStatus(BoolEnum.TRUE.getType());
                                        eduHouse.setPrimarySchoolOne("100%");
                                    } else {
                                        if(qlbl==0){
                                            eduHouse.setAuthStatus(AuthStatusEnum.NODO.getType());
                                            eduHouse.setStatus(BoolEnum.TRUE.getType());
                                            if (!statusFlag) {
                                                eduHouse.setRemark("系统判断权利人2个,不动产未返回占有比例，需要人工核验份额（" + JSON.toJSONString(vo.getAllIdcardList()) + "）和（" + JSON.toJSONString(qlrList) + "）");
                                            }
                                        }else{
                                            if(qlbl>=50){
                                                eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                                                eduHouse.setStatus(BoolEnum.TRUE.getType());
                                                if (!statusFlag) {
                                                    eduHouse.setRemark("系统判断权利人大于2个且分额大于等于51%，设置为有效");
                                                }
                                            }else{
                                                eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                                                eduHouse.setStatus(BoolEnum.FALSE.getType());
                                                if (!statusFlag) {
                                                    eduHouse.setRemark("系统判断权利人大于2个且分额不足50%，设置为无效（" + JSON.toJSONString(vo.getAllIdcardList()) + "）和（" + JSON.toJSONString(qlrList) + "）");
                                                }
                                            }
                                        }

                                    }
                                } else {
                                    //用姓名来比对
                                    if (vo.getAllNameList().containsAll(qlrNameList)) {
                                        eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                                        eduHouse.setStatus(BoolEnum.TRUE.getType());
                                        eduHouse.setPrimarySchoolOne("100%");
                                    } else {
                                        if(qlbl==0){
                                            eduHouse.setAuthStatus(AuthStatusEnum.NODO.getType());
                                            eduHouse.setStatus(BoolEnum.TRUE.getType());
                                            if (!statusFlag) {
                                                eduHouse.setRemark("系统判断权利人2个,不动产未返回占有比例，需要人工核验份额（" + JSON.toJSONString(vo.getAllIdcardList()) + "）和（" + JSON.toJSONString(qlrList) + "）");
                                            }
                                        }else{
                                            if(qlbl>=50){
                                                eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                                                eduHouse.setStatus(BoolEnum.TRUE.getType());
                                                if (!statusFlag) {
                                                    eduHouse.setRemark("系统判断权利人2个且分额大于等于51%，设置为有效");
                                                }
                                            }else{
                                                eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                                                eduHouse.setStatus(BoolEnum.FALSE.getType());
                                                if (!statusFlag) {
                                                    eduHouse.setRemark("系统判断权利人2个且分额不足50%，设置为无效（" + JSON.toJSONString(vo.getAllIdcardList()) + "）和（" + JSON.toJSONString(qlrList) + "）");
                                                }
                                            }
                                        }
                                    }
                                }

                            } else {
                                //遇到身份证返回为空情况，用姓名来比对
                                if (vo.getAllNameList().containsAll(qlrNameList)) {
                                    eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                                    eduHouse.setStatus(BoolEnum.TRUE.getType());
                                    eduHouse.setPrimarySchoolOne("100%");
                                } else {
                                    if(qlbl==0){
                                        eduHouse.setAuthStatus(AuthStatusEnum.NODO.getType());
                                        eduHouse.setStatus(BoolEnum.TRUE.getType());
                                        if (!statusFlag) {
                                            eduHouse.setRemark("系统判断权利人2个,不动产未返回占有比例，需要人工核验份额（" + JSON.toJSONString(vo.getAllIdcardList()) + "）和（" + JSON.toJSONString(qlrList) + "）");
                                        }
                                    }else{
                                        if(qlbl>=50){
                                            eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                                            eduHouse.setStatus(BoolEnum.TRUE.getType());
                                            if (!statusFlag) {
                                                eduHouse.setRemark("系统判断权利人2个且分额大于等于51%，设置为有效");
                                            }
                                        }else{
                                            eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                                            eduHouse.setStatus(BoolEnum.FALSE.getType());
                                            if (!statusFlag) {
                                                eduHouse.setRemark("系统判断权利人2个且分额不足50%，设置为无效（" + JSON.toJSONString(vo.getAllIdcardList()) + "）和（" + JSON.toJSONString(qlrList) + "）");
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            //没有权利人，直接无效
                            eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                            eduHouse.setStatus(BoolEnum.FALSE.getType());
                            if (!statusFlag) {
                                eduHouse.setRemark("系统判断没有权利人设置为无效");
                            }
                        }
                        if (!ObjectUtils.isEmpty(house.getTdsyjssj())
                                && !ObjectUtils.isEmpty(house.getTdsyqssj())) {
                            int betweenYear =
                                    (int)
                                            DateUtil.betweenYear(
                                                    DateUtil.offsetDay(
                                                            DateUtil.parse(
                                                                    house.getTdsyqssj(),
                                                                    "yyyy年MM月dd日"),
                                                            -1),
                                                    DateUtil.parse(
                                                            house.getTdsyjssj(),
                                                            "yyyy年MM月dd日"),
                                                    false);
                            eduHouse.setYearLimit(betweenYear);
                        } else {
                            eduHouse.setYearLimit(100);
                        }
                        if (eduHouse.getYearLimit() > 20 && eduHouse.getYearLimit() <= 40) {
                            //小于70年产权的，全部设置不通过
                            eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                            eduHouse.setStatus(BoolEnum.FALSE.getType());
                            if (!statusFlag) {
                                eduHouse.setRemark("系统判断产权20和40年之间设置为无效");
                            }
                        }
                        if (!ObjectUtils.isEmpty(odlHouse)) {
                            eduHouse.setRemark(odlHouse.getRemark());
                            eduHouse.setStreet(odlHouse.getStreet());
                        }

                        //不动产权号关键字过滤
                        if (!ObjectUtils.isEmpty(realProperty)
                                && (realProperty.contains("证明")
                                || realProperty.contains("预"))) {
                            //带证明和预字的设置为无效
                            eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                            eduHouse.setStatus(BoolEnum.FALSE.getType());
                            if (!statusFlag) {
                                eduHouse.setRemark("系统判断房产证号上带有“证明”或“预”设置为无效");
                            }
                        }
                        //地址关键字过滤
                        if (!CollectionUtils.isEmpty(glAddressList)) {
                            for (String glStr : glAddressList) {
                                if (eduHouse.getAddress().contains(glStr)) {
                                    eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                                    eduHouse.setStatus(BoolEnum.FALSE.getType());
                                    if (!statusFlag) {
                                        eduHouse.setRemark("系统判断地址上有不能使用的关键字(" + glStr + ")设置为无效");
                                    }

                                    break;
                                }
                            }
                        }
                        //房产类型过滤
                        if (!CollectionUtils.isEmpty(fclxList)) {
                            if (StringUtils.isNotBlank(eduHouse.getLandCategoriesName())) {
                                boolean lxFlag=false;
                                for(String str:fclxList){
                                    if(str.indexOf("=")>=0){
                                        if(eduHouse.getLandCategoriesName().equalsIgnoreCase(str.replace("=",""))){
                                            lxFlag=true;
                                            break;
                                        }
                                    }else{
                                        if (eduHouse.getLandCategoriesName().indexOf(str)>=0){
                                            lxFlag=true;
                                            break;
                                        }
                                    }
                                }
                                if(lxFlag){
                                    eduHouse.setAuthStatus(AuthStatusEnum.NO.getType());
                                    eduHouse.setStatus(BoolEnum.FALSE.getType());
                                    if (!statusFlag) {
                                        eduHouse.setRemark("系统判断地址上有土地使用类型为(" + eduHouse.getLandCategoriesName() + ")设置为无效");
                                    }
                                }

                            }

                        }

                        boolean detailFlag = true;
                        if (newFlag) {
                            detailFlag = true;
                            //新增
                        } else {
                            List<EduHouseDetail> details = oldGroupByFinal.get(eduHouse.getHouseId());
                            if (!CollectionUtils.isEmpty(details)) {
                                for (HouseInterfaceDetailVO qlrxx : house.getQlrxxList()) {
                                    EduHouseDetail detail = new EduHouseDetail();
                                    String qlrZjh = qlrxx.getZjh().toUpperCase();
                                    if (qlrZjh.length() == 15) {
                                        qlrZjh = IdcardUtil.convert15To18(qlrZjh);
                                    }
                                    detail.setHouseId(eduHouse.getHouseId());
                                    detail.setRealProperty(qlrxx.getBdcqzh());
                                    detail.setIdcard(qlrZjh);
                                    if(StringUtils.isNotBlank(qlrxx.getQlbl())){
                                        detail.setObligee(qlrxx.getQlbl().replaceAll("%","").trim());
                                    }
                                    detail.setFullName(qlrxx.getQlr());
                                    detail.setCommonSituation(saveDict("COMMONSITUATION", qlrxx.getGyfs(), vo.getAccessToken()));
                                    detail.setCommonSituationName(qlrxx.getGyfs());
                                    detail.setYear(eduHouse.getYear());
                                    detail.setStatus("1");
                                    detail.setHouseDetailId(IdUtil.simpleUUID());
                                    for (EduHouseDetail houseDetail : details) {
                                        if (StringUtils.isBlank(qlrZjh)) {
                                            if (qlrxx.getQlr().equals(houseDetail.getFullName()) && qlrxx.getBdcqzh().equals(houseDetail.getRealProperty())) {
                                                detail.setHouseDetailId(houseDetail.getHouseDetailId());
                                                break;
                                            }
                                        } else {
                                            if (StringUtils.isNotBlank(houseDetail.getIdcard()) && qlrZjh.equals(houseDetail.getIdcard().toUpperCase())) {
                                                detail.setHouseDetailId(houseDetail.getHouseDetailId());
                                                break;
                                            }
                                        }
                                    }


                                    detailList.add(detail);
                                }
                                for (EduHouseDetail houseDetail : details) {
                                    boolean flag = true;
                                    for (HouseInterfaceDetailVO qlrxx : house.getQlrxxList()) {
                                        String qlrZjh = qlrxx.getZjh().toUpperCase();
                                        if (qlrZjh.length() == 15) {
                                            qlrZjh = IdcardUtil.convert15To18(qlrZjh);
                                        }
                                        if (StringUtils.isBlank(qlrZjh)) {
                                            if (qlrxx.getQlr().equals(houseDetail.getFullName()) && qlrxx.getBdcqzh().equals(houseDetail.getRealProperty())) {
                                                flag = false;
                                                break;
                                            }
                                        } else {
                                            if (StringUtils.isNotBlank(houseDetail.getIdcard()) && qlrZjh.equals(houseDetail.getIdcard().toUpperCase())) {
                                                flag = false;
                                                break;
                                            }
                                        }
                                    }
                                    if (flag) {
                                        eduHouseDetailService.removeById(houseDetail.getHouseDetailId());
                                    }

                                }
                                detailFlag = false;
                            } else {
                                QueryWrapper<EduHouseDetail> delQuery = new QueryWrapper<>();
                                delQuery.lambda().eq(EduHouseDetail::getHouseId, eduHouse.getHouseId());
                                eduHouseDetailService.remove(delQuery);
                                detailFlag = true;

                            }
                        }
                        if (detailFlag) {
                            house.getQlrxxList().forEach(
                                    qlrxx -> {
                                        EduHouseDetail detail = new EduHouseDetail();
                                        detail.setHouseDetailId(IdUtil.simpleUUID());
                                        detail.setHouseId(eduHouse.getHouseId());
                                        detail.setRealProperty(qlrxx.getBdcqzh());
                                        String qlrZjh = qlrxx.getZjh().toUpperCase();
                                        if (qlrZjh.length() == 15) {
                                            qlrZjh = IdcardUtil.convert15To18(qlrZjh);
                                        }
                                        detail.setIdcard(qlrZjh);
                                        detail.setFullName(qlrxx.getQlr());

                                        if(StringUtils.isNotBlank(qlrxx.getQlbl())){
                                            detail.setObligee(qlrxx.getQlbl().replaceAll("%","").trim());
                                        }
                                        detail.setCommonSituation(saveDict("COMMONSITUATION", qlrxx.getGyfs(), vo.getAccessToken()));
                                        detail.setCommonSituationName(qlrxx.getGyfs());
                                        detail.setYear(eduHouse.getYear());
                                        detail.setStatus(eduHouse.getStatus());
                                        detailList.add(detail);
                                    });
                        }

                    } else {
                        if (!newFlag) {
                            QueryWrapper<EduHouseDetail> delQuery = new QueryWrapper<>();
                            delQuery.lambda().eq(EduHouseDetail::getHouseId, eduHouse.getHouseId());
                            eduHouseDetailService.remove(delQuery);
                        }
                    }
                    if (!statusFlag && BoolEnum.TRUE.getType().equalsIgnoreCase(eduHouse.getStatus())) {
                        eduHouse.setRemark("");
                    }
                    if (vo.getOneFlag() == null || !vo.getOneFlag()) {
                        if (StringUtils.isNotBlank(status)) {
                            eduHouse.setStatus(status);
                        }
                        if (StringUtils.isNotBlank(authStatus)) {
                            eduHouse.setAuthStatus(authStatus);
                        }
                    } else {
                        //只有父母一方的，使用已有状态
                        if (StringUtils.isNotBlank(status)) {
                            eduHouse.setStatus(status);
                        }
                        if (StringUtils.isNotBlank(authStatus)) {
                            eduHouse.setAuthStatus(authStatus);
                        }

                    }
                    if(StringUtils.isNotBlank(eduHouse.getAddress())) {
                        if (eduHouse.getStatus().equals(BoolEnum.TRUE.getType())) {
                            String addressId =
                                    eduAddressService.saveByAddress(eduHouse.getAddress(), eduHouse.getYear(), vo.getBnxxFlag(), vo.getBnczFlag());
                            eduHouse.setAddressId(addressId);
                        }
                        eduHouse.setAreaCode(areaCode);
                        eduHouseService.saveOrUpdate(eduHouse);
                        if (!CollectionUtils.isEmpty(detailList)) {
                            eduHouseDetailService.saveOrUpdateBatch(detailList);
                        }
                        EduHouseVO houseVO = Convert.convert(EduHouseVO.class, eduHouse);

                        List<EduHouseDetailVO> detailVOList = Convert.toList(EduHouseDetailVO.class, detailList);
                        houseVO.setDetailList(detailVOList);
                        eduHouseVOList.add(houseVO);
                    }

                }
            }
            List<String> delHouseIdList = new ArrayList<>();
            if (CollectionUtils.isEmpty(oldHouseIdList)) {
                delHouseIdList.addAll(houseIdList);
            } else {
                for (String houseId : houseIdList) {
                    if (!oldHouseIdList.contains(houseId)) {
                        delHouseIdList.add(houseId);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(delHouseIdList)) {
                QueryWrapper<EduHouseDetail> detailQueryWrapper = new QueryWrapper<>();
                detailQueryWrapper.lambda().in(EduHouseDetail::getHouseId, delHouseIdList);
                eduHouseDetailService.remove(detailQueryWrapper);
                eduHouseService.removeByIds(delHouseIdList);
            }
        } catch (AppException e) {
            logger.error("房产获取异常"+e.getMsg());
            throw e;
        } catch (Exception e) {
            logger.error("房产获取异常"+e.getMessage());
            throw new AppException(e.getMessage());
        }
        return eduHouseVOList;
    }


    @Override
    @OpApi(funcCode = "F3307000003", title = "金华网签接口信息获取并保存", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduNetsignVO> saveNetsignInterfaceData(NetsignSaveVO vo) {

        boolean replaceFlag = vo.getReplaceFlag();
        int year = operationCacheIntegration.getPeriodYear().getYear();
        List<WqVO> houseOnline = new ArrayList<>();//dygxIntegration.getHouseOnline(vo.getIdcard());
        List<EduNetsign> netsignList = Convert.toList(EduNetsign.class, houseOnline);

        QueryWrapper<EduNetsign> netsignQueryWrapper = new QueryWrapper<>();
        netsignQueryWrapper
                .lambda()
                .eq(EduNetsign::getIdcard, vo.getIdcard())
                .isNull(EduNetsign::getSchoolId)
                .eq(EduNetsign::getYear, year);
        List<EduNetsign> oldList = eduNetsignService.list(netsignQueryWrapper);
        if (oldList.size() > 0) {
            if (replaceFlag) {
                eduNetsignService.removeByIds(
                        oldList.stream()
                                .map(EduNetsign::getNetsignId)
                                .collect(Collectors.toList()));
            } else {
                return Convert.toList(EduNetsignVO.class, oldList);
            }
        }

        netsignList.forEach(
                item -> {
                    item.setNetsignId(IdUtil.simpleUUID());
                    item.setStatus(BoolEnum.TRUE.getType());
                    item.setYear(year);
                    item.setAreaCode(areaCode);
                    if (StringUtils.isBlank(item.getIdcard())) {
                        item.setIdcard(vo.getIdcard());
                    }
                    //网签暂不进地址池
                    /***
                     String addressId =
                     eduAddressService.saveByAddress(item.getDz());
                     item.setAddressId(addressId);
                     ***/
                });
        eduNetsignService.saveBatch(netsignList);
        return Convert.toList(EduNetsignVO.class, netsignList);
    }

    @Override
    @OpApi(funcCode = "F3307000025", title = "金华根据购房合同编号获取网签接口信息获取并保存", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduNetsignVO> saveNetsignJhInterfaceData(NetsignSaveVO vo) {
        return null;
    }

    @Override
    @OpApi(funcCode = "F3307000004", title = "金华参保接口信息获取并保存", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduSocialSecurityVO> saveCbInterfaceData(CbSaveVO vo) {
        boolean replaceFlag = vo.getReplaceFlag();
        int year = operationCacheIntegration.getPeriodYear().getYear();
        JSONArray grcbDy = jhIrsIntegration.getCbIrs(vo.getIdcard(),vo.getReqIp());
        List<EduSocialSecurity> socialSecurityList =new ArrayList<>();
        if(grcbDy!=null&&grcbDy.size()>0){
            for(int i=0;i<grcbDy.size();i++){
                EduSocialSecurity socialSecurity=new EduSocialSecurity();
                JSONObject jsonObject=grcbDy.getJSONObject(i);
                socialSecurity.setAab301(jsonObject.getString("AAB301"));
                socialSecurity.setAab001(jsonObject.getString("AAB001"));
                socialSecurity.setAab004(jsonObject.getString("AAB004"));
                socialSecurity.setAac001(jsonObject.getString("AAC001"));
                socialSecurity.setAac002(jsonObject.getString("AAC002"));
                socialSecurity.setAac147(jsonObject.getString("AAC147"));
                socialSecurity.setAac003(jsonObject.getString("AAC003"));
                socialSecurity.setAac008(jsonObject.getString("AAC008"));
                socialSecurity.setAac031(jsonObject.getString("AAC031"));
                socialSecurity.setAac058(jsonObject.getString("AAC058"));
                socialSecurity.setAae030(jsonObject.getString("AAE030"));
                socialSecurity.setAae031(jsonObject.getString("AAE031"));
                socialSecurity.setAae140(jsonObject.getString("AAE140"));
                socialSecurity.setBab010(jsonObject.getString("BAB010"));
                socialSecurity.setBaz159(jsonObject.getString("BAZ159"));
                if((socialSecurity.getAab301().equalsIgnoreCase("330799")
                        ||socialSecurity.getAab301().equalsIgnoreCase("330702")
                        ||socialSecurity.getAab301().equalsIgnoreCase("330703")
                        ||socialSecurity.getAab301().equalsIgnoreCase("330704"))&&(
                        "110".equalsIgnoreCase(socialSecurity.getAae140()) || "120".equalsIgnoreCase(socialSecurity.getAae140()))){
                    socialSecurityList.add(socialSecurity);
                }

            }
        }

        QueryWrapper<EduSocialSecurity> socialSecurityQueryWrapper = new QueryWrapper<>();
        socialSecurityQueryWrapper
                .lambda()
                .eq(EduSocialSecurity::getSourceType, SourceTypeEnum.gx.getType())
                .eq(EduSocialSecurity::getAac147, vo.getIdcard())
                .eq(EduSocialSecurity::getYear, year);
        List<EduSocialSecurity> oldList = eduSocialSecurityService.list(socialSecurityQueryWrapper);
        if (oldList.size() > 0) {
            if (replaceFlag) {
                eduSocialSecurityService.removeByIds(
                        oldList.stream()
                                .map(EduSocialSecurity::getSocialSecurityId)
                                .collect(Collectors.toList()));
            } else {
                return Convert.toList(EduSocialSecurityVO.class, oldList);
            }
        }

        for (EduSocialSecurity item : socialSecurityList) {
            item.setSocialSecurityId(IdUtil.simpleUUID());
            item.setYear(year);
            item.setSourceType(SourceTypeEnum.gx.getType());
            item.setTotalFlag(BoolEnum.FALSE.getType());
            item.setTotalErrorCnt(0);
            if ((item.getAab301().equalsIgnoreCase("330799")
                    ||item.getAab301().equalsIgnoreCase("330702")
                    ||item.getAab301().equalsIgnoreCase("330703")
                    ||item.getAab301().equalsIgnoreCase("330704"))&&(
            "110".equalsIgnoreCase(item.getAae140()) || "120".equalsIgnoreCase(item.getAae140()))) {
                getSocialSecurityDetail(item,vo.getReqIp());
            }

        }

        eduSocialSecurityService.saveOrUpdateBatch(socialSecurityList);
        return Convert.toList(EduSocialSecurityVO.class, socialSecurityList);
    }

    @Override
    @OpApi(funcCode = "F3307000024", title = "金华省参保缴费明细接口信息获取并保存", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void saveCbJfInterfaceData(EduSocialSecurity item,String ip) {
        getSocialSecurityDetail(item,ip);
        eduSocialSecurityService.updateById(item);
    }

    private void getSocialSecurityDetail(EduSocialSecurity item,String ip){
        Integer year=item.getYear();
        String aae030="201001";
        String aae031=DateUtil.format(new Date(),"YYYYMM");
        //删除之前缴费明细数据
        QueryWrapper<EduSocialSecurityDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSocialSecurityDetail::getAac147, item.getAac147())
                .eq(EduSocialSecurityDetail::getYear, year);
        eduSocialSecurityDetailService.remove(queryWrapper);
        if ("1".equalsIgnoreCase(item.getAac008()) && "1".equalsIgnoreCase(item.getAac031())) {
            try {
                List<EduSocialSecurityDetail> detailList=new ArrayList<>();
                JSONArray jsonArray = jhIrsIntegration.getCbJfIrs(item.getAac002(),item.getAac003(),aae030,aae031,item.getAae140(),"",ip);
                int jfzys=0;
                int bdwlj=0;
                for(int i=0;i<jsonArray.size();i++){
                    EduSocialSecurityDetail detail=new EduSocialSecurityDetail();
                    JSONObject jsonObject=jsonArray.getJSONObject(i);
                    detail.setYear(year);
                    detail.setAab301(jsonObject.getString("aab301"));
                    detail.setAaa027(jsonObject.getString("aaa027"));
                    detail.setBaa115(jsonObject.getString("baa115"));
                    detail.setAab001(jsonObject.getString("bab010"));//没有返回单位id用统一社会信用代码传入
                    detail.setAac003(jsonObject.getString("aac003"));
                    detail.setAac147(jsonObject.getString("aac002"));
                    detail.setAae140(item.getAae140());
                    detail.setAae003(jsonObject.getString("aae003"));
                    detail.setAae018(jsonObject.getString("aab004"));//存放单位名称
                    detail.setSocialSecurityId(item.getSocialSecurityId());
                    if("正常应缴".equalsIgnoreCase(detail.getBaa115())){
                        jfzys=jfzys+1;//同单位累计缴费月数
                    }
                    if(StringUtils.isNotBlank(detail.getAab001())&&StringUtils.isNotBlank(item.getBab010())){
                        if("正常应缴".equalsIgnoreCase(detail.getBaa115())&&item.getBab010().equalsIgnoreCase(detail.getAab001())){
                            bdwlj=bdwlj+1;//同单位累计缴费月数
                        }
                    }else{
                        if("正常应缴".equalsIgnoreCase(detail.getBaa115())&&StringUtils.isNotBlank(detail.getAae018())&&StringUtils.isNotBlank(item.getAab004())&&detail.getAae018().equalsIgnoreCase(item.getAab004())){
                            bdwlj=bdwlj+1;//同单位累计缴费月数
                        }
                    }
                    detailList.add(detail);

                }
                item.setTotal(jfzys);
                item.setTotalBc(bdwlj);
                if (!CollectionUtils.isEmpty(detailList)) {
                    item.setTotalFlag("1");
                    item.setTotalRemarks("获取缴费明细成功");
                    item.setTotalTime(new Date());
                    detailList = detailList.stream().sorted(Comparator.comparing(EduSocialSecurityDetail::getAae003, Comparator.reverseOrder())).collect(Collectors.toList());
                    Date curTime = DateUtil.offsetMonth(new Date(), -2);
                    int count = 0;
                    int i = 0;
                    int bdwlx=0;
                    boolean lxFlag=true;
                    Map<String,String> map=new HashMap<>();
                    List<EduSocialSecurityDetail> saveDetailList=new ArrayList<>();
                    for (EduSocialSecurityDetail eduSocialSecurityDetail : detailList) {
                        eduSocialSecurityDetail.setSocialSecurityId(item.getSocialSecurityId());
                        eduSocialSecurityDetail.setYear(year);
                        saveDetailList.add(eduSocialSecurityDetail);

                    }
                    for (EduSocialSecurityDetail eduSocialSecurityDetail : saveDetailList) {
                        int thisMonth = Integer.parseInt(DateUtil.format(curTime, "YYYYMM"));

                        if (StringUtils.isNotBlank(eduSocialSecurityDetail.getAae003())) {
                            if( thisMonth == Integer.parseInt(eduSocialSecurityDetail.getAae003())) {

                                count = count + 1;
                                if((StringUtils.isNotBlank(eduSocialSecurityDetail.getAab001())&&StringUtils.isNotBlank(item.getBab010())&&eduSocialSecurityDetail.getAab001().equalsIgnoreCase(item.getBab010()))
                                        ||(StringUtils.isNotBlank(eduSocialSecurityDetail.getAae018())&&StringUtils.isNotBlank(item.getAab004())&&eduSocialSecurityDetail.getAae018().equalsIgnoreCase(item.getAab004()))){
                                    //同一个单位
                                    if(lxFlag){
                                        bdwlx=bdwlx+1;
                                    }

                                }else{
                                    lxFlag=false;
                                }

                            }else if(thisMonth < Integer.parseInt(eduSocialSecurityDetail.getAae003())){
                                continue;
                            }else{
                                break;
                            }
                        } else {
                            break;
                        }
                        i = i + 1;
                        curTime = DateUtil.offsetMonth(curTime, -1);

                    }
                    if (count >= 5) {
                        item.setContinuityFlag(BoolEnum.TRUE.getType());
                    } else {
                        item.setContinuityFlag(BoolEnum.FALSE.getType());
                    }
                    eduSocialSecurityDetailService.saveBatch(saveDetailList);
                } else {
                    item.setTotalFlag("1");
                    item.setTotalRemarks("获取成功，大数据返回无缴费明细");
                    item.setContinuityFlag(BoolEnum.FALSE.getType());
                    item.setContinuityMsg("获取成功，大数据返回无缴费明细");
                }
                item.setTotalBclx(bdwlj);

            } catch (AppException e) {
                logger.error("获取社保缴费明细信息异常"+e.getMsg());
                item.setContinuityFlag(BoolEnum.FALSE.getType());
                String msg=e.getMsg();
                if(StringUtils.isNotBlank(msg)&&msg.length()>300){
                    msg=msg.substring(0,260);
                }
                item.setContinuityMsg(msg);
                item.setTotalFlag("2");
                item.setTotalRemarks(msg);
            } catch (Exception e) {
                logger.error("获取社保缴费明细信息异常"+e.getMessage());
                item.setContinuityFlag(BoolEnum.FALSE.getType());
                String msg=e.getMessage();
                if(StringUtils.isNotBlank(msg)&&msg.length()>300){
                    msg=msg.substring(0,260);
                }
                item.setContinuityMsg(msg);
                item.setTotalFlag("2");
                item.setTotalRemarks(msg);
            }
        }

    }
    @Override
    @OpApi(funcCode = "F3307000005", title = "金华企业接口信息获取并保存", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduCompanyVO> saveQyInterfaceData(QySaveVO vo) {
        return new ArrayList<>();
    }

    @Override
    @OpApi(funcCode = "F3307000006", title = "金华居住证接口信息获取并保存", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduLivePlaceVO> saveJzzInterfaceData(JzzSaveVO vo) {
        boolean replaceFlag = vo.getReplaceFlag();
        int year = operationCacheIntegration.getPeriodYear().getYear();
        if (vo.getLocalFlag() == null) {
            vo.setLocalFlag(true);
        }
        QueryWrapper<EduLivePlace> livePlaceQueryWrapper = new QueryWrapper<>();
        livePlaceQueryWrapper
                .lambda()
                .eq(EduLivePlace::getSourceType, SourceTypeEnum.gx.getType())
                .eq(EduLivePlace::getSfzh, vo.getIdcard())
                .eq(EduLivePlace::getYear, year);


        List<EduLivePlace> oldList = eduLivePlaceService.list(livePlaceQueryWrapper);
        if (!CollectionUtils.isEmpty(oldList)) {
            if (!replaceFlag) {
                return Convert.toList(EduLivePlaceVO.class, oldList);
            }
        }
        List<DyJzzVO> jzzVOList = new ArrayList<>();

        //同步调用，服务器网络和irs省网络联通条件下可直接调用
        JSONArray jsonArray = jhIrsIntegration.getJzzIrs(vo.getIdcard(), vo.getName(),vo.getReqIp());
        if (jsonArray != null && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject dataAll = jsonArray.getJSONObject(i);
                if (dataAll.get("ELC_LICENCE_STRUCT")==null){
                    continue;
                }
                JSONObject dataS = dataAll.getJSONObject("ELC_LICENCE_STRUCT");
                if (dataS.get("DATA")==null){
                    continue;
                }
                JSONObject data=dataS.getJSONObject("DATA");
                DyJzzVO jzzVO = new DyJzzVO();
                jzzVO.setSfzh(data.getString("SFZH"));
                jzzVO.setXm(data.getString("XM"));
                jzzVO.setXb(data.getString("XB"));
                jzzVO.setZjnbbh(data.getString("ZJNBBH"));
                jzzVO.setZjzt(data.getString("ZJZT"));
                jzzVO.setMz(data.getString("MZ"));
                jzzVO.setJzdz(data.getString("JZDZ"));
                jzzVO.setHjdz(data.getString("HJDZ"));
                jzzVO.setHksxdm(data.getString("HKSXDM"));
                jzzVO.setHksx(data.getString("HKSX"));
                jzzVO.setQzrq(data.getString("FZRQ"));
                jzzVO.setFzdgajg(data.getString("FZDGAJG"));
                if(StringUtils.isNotBlank(jzzVO.getFzdgajg())&&jzzVO.getFzdgajg().indexOf("金华市")>=0) {
                    if (jzzVO.getFzdgajg().indexOf("江南分局") >= 0) {
                        jzzVO.setXzqhdm("330704");
                    }
                    if (jzzVO.getFzdgajg().indexOf("婺城") >= 0) {
                        jzzVO.setXzqhdm("330702");
                    }
                    if (jzzVO.getFzdgajg().indexOf("金东") >= 0) {
                        jzzVO.setXzqhdm("330703");
                    }
                    if("正常".equalsIgnoreCase(jzzVO.getZjzt())){
                        jzzVO.setZjztdm("2");
                    }
                    jzzVO.setAreaCode(jzzVO.getXzqhdm());
                    jzzVOList.add(jzzVO);
                }

            }
        }



        if (CollectionUtils.isEmpty(jzzVOList)) {
            if (!CollectionUtils.isEmpty(oldList) && replaceFlag) {
                eduLivePlaceService.removeByIds(
                        oldList.stream()
                                .map(EduLivePlace::getLivePlaceId)
                                .collect(Collectors.toList()));
            }
            return new ArrayList<>();
        }
        List<EduLivePlace> livePlaceList = Convert.toList(EduLivePlace.class, jzzVOList);
        livePlaceList.forEach(
                item -> {
                    item.setLivePlaceId(IdUtil.simpleUUID());
                    if (!CollectionUtils.isEmpty(oldList)) {
                        for (EduLivePlace eduLivePlace : oldList) {
                            if (StringUtils.isNotBlank(eduLivePlace.getZjnbbh())&&eduLivePlace.getZjnbbh().equalsIgnoreCase(item.getZjnbbh())) {
                                item.setLivePlaceId(eduLivePlace.getLivePlaceId());
                                break;
                            }
                        }
                    }
                    item.setYear(year);
                    item.setSourceType(SourceTypeEnum.gx.getType());
                    if (StringUtils.isBlank(item.getAreaCode())){
                        item.setAreaCode(item.getXzqhdm());
                    }
                });
        if (!CollectionUtils.isEmpty(oldList)) {
            for (EduLivePlace old : oldList) {
                boolean flag = true;
                for (EduLivePlace newPlace : livePlaceList) {
                    if (StringUtils.isNotBlank(newPlace.getZjnbbh())&&newPlace.getZjnbbh().equalsIgnoreCase(old.getZjnbbh())) {
                        flag = false;
                    }
                }
                if (flag) {
                    eduLivePlaceService.removeById(old.getLivePlaceId());
                }
            }
        }
        eduLivePlaceService.saveOrUpdateBatch(livePlaceList);
        return Convert.toList(EduLivePlaceVO.class, livePlaceList);
    }

    @Override
    @OpApi(funcCode = "F3307000007", title = "金华单个可报名数据生成", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    @Transactional
    public int createEnrollBefore(EduStudentEnrollPre eduStudentEnrollPre) {
        int count= 0;
        try {
            count = createBefore(eduStudentEnrollPre);
            eduEnrollClearCacheHelper.clearCachePreBefore(eduStudentEnrollPre.getStudentEnrollPreId());
        } catch (AppException e) {
            throw new AppException(e.getMessage());
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        return count;
    }

    @Override
    @OpApi(funcCode = "F3307000013", title = "金华批量生成预测数据", funcType = FuncTypeEnum.edit, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void createCalculateBatch(BatchCreateVO vo) {
        createCalculateBatchPageInfo(vo);
    }


    @Override
    @OpApi(funcCode = "F3307000008", title = "金华我的报名查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void getMyEnrollInfo(List<StudentFormVO> myEnrollInfo) {

        EduOperationCacheQueryVO queryVO = new EduOperationCacheQueryVO();
        queryVO.setAreaCode(areaCode);
        queryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = operationCacheIntegration.getEduOperation(queryVO);
        int year = eduOperationCacheVO.getYear();

        for (StudentFormVO studentFormVO : myEnrollInfo) {
            if ("1".equals(studentFormVO.getSchoolCategory())) {
                if (AuthStatusEnum.NODO.getType().equals(studentFormVO.getAuthStatus())) {
                    studentFormVO.setEnrollStatus("0");
                    studentFormVO.setEnrollStatusName("待审核");
                } else if (AuthStatusEnum.YES.getType().equals(studentFormVO.getAuthStatus())) {
                    if (StringUtils.isBlank(studentFormVO.getAdmitFlag())) {
                        studentFormVO.setEnrollStatus("1");
                        studentFormVO.setEnrollStatusName("资料审核通过，等待终审录取");
                    } else {
                        if (BoolEnum.TRUE.getType().equals(studentFormVO.getAdmitFlag())) {
                            studentFormVO.setEnrollStatus("2");
                            studentFormVO.setEnrollStatusName("已录取");
                        } else {
                            studentFormVO.setEnrollStatus("3");
                            studentFormVO.setEnrollStatusName("不予录取");
                        }
                    }
                } else if (AuthStatusEnum.NO.getType().equals(studentFormVO.getAuthStatus())) {
                    studentFormVO.setEnrollStatus("3");
                    studentFormVO.setEnrollStatusName("不予录取");
                }
            } else {
                if ("0".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("待审核");
                } else if ("1".equals(studentFormVO.getEnrollStatus())) {
                    if("1".equalsIgnoreCase(studentFormVO.getImitateFlag())){
                        studentFormVO.setEnrollStatusName("模拟报名学校审核通过");
                    }else{
                        studentFormVO.setEnrollStatusName("学校初审通过，等待复审");
                    }

                } else if ("2".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("已录取");
                } else if ("3".equals(studentFormVO.getEnrollStatus())) {
                    if(AuthStatusEnum.NO.getType().equalsIgnoreCase(studentFormVO.getAuthStatus())){
                        if("3".equalsIgnoreCase(studentFormVO.getIcertificatioFlag())){
                            studentFormVO.setEnrollStatusName("资料核验不通过");
                        }else{
                            studentFormVO.setEnrollStatusName("审核不通过");
                        }

                    }else{
                        studentFormVO.setEnrollStatusName("终审不通过，不予录取");
                    }

                } else if ("4".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("报名无效");
                } else if ("5".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("未派中");
                } else if ("6".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("主动退出");
                }else if ("7".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("待审核");
                }else if ("8".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("复审通过");
                }else if ("9".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("资料核验不通过");
                }else if ("10".equals(studentFormVO.getEnrollStatus())) {
                    studentFormVO.setEnrollStatusName("待重新提交资料");
                }
            }

            if (studentFormVO.getYear() < year) {
                continue;
            }
            Map<String, EduOperationCacheDetailVO> operation = eduOperationCacheVO.getOperation();
            if (operation != null) {
                if ("1".equals(studentFormVO.getSchoolCategory())) {
                    //幼儿园
                    continue;
                } else {
                    if ("0".equals(studentFormVO.getSchoolNature())) {
                        EduOperationCacheDetailVO detailVO = operation.get("YW003");
                        //公办
                        if (detailVO.getEndTime() != null) {
                            studentFormVO.setEndAuditTime(DatePattern.CHINESE_DATE_FORMAT.format(detailVO.getEndTime()));
                        }
                    } else if ("1".equals(studentFormVO.getSchoolNature())) {
                        //民办
                        EduOperationCacheDetailVO detailVO = operation.get("YW007");
                        if (detailVO.getEndTime() != null) {
                            studentFormVO.setEndAuditTime(DatePattern.CHINESE_DATE_FORMAT.format(detailVO.getEndTime()));
                        }
                    } else if ("2".equals(studentFormVO.getSchoolNature())) {
                        //民转公
                        EduOperationCacheDetailVO detailVO = operation.get("YW014");
                        if (detailVO.getEndTime() != null) {
                            studentFormVO.setEndAuditTime(DatePattern.CHINESE_DATE_FORMAT.format(detailVO.getEndTime()));
                        }
                    }
                }
            }
        }

    }

    @Override
    @OpApi(funcCode = "F3307000009", title = "金华家庭成员比对接口", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public String getFamInfoComparison(EduStudentEnrollPreKeyVO vo) {
        EduStudentEnrollPre eduStuEnrollPre = eduStudentEnrollPreService.getById(vo.getStudentEnrollPreId());
        if (eduStuEnrollPre == null) {
            throw new AppException("未找到预采集数据");
        }
        String infoComparison = "4";
        //判断户籍和房产是获取
        if(!BoolEnum.TRUE.getType().equalsIgnoreCase(eduStuEnrollPre.getHouseholdSyncFlag())||!BoolEnum.TRUE.getType().equalsIgnoreCase(eduStuEnrollPre.getHouseSyncFlag())){
            return "0";
        }
        infoComparison = this.getStuFamInfoComparison(eduStuEnrollPre);
        String msg = "";
        switch (infoComparison) {
            case "1":
                msg = "比对通过";
                break;
            case "2":
                msg = "父亲通过母亲不通过";
                break;
            case "3":
                msg = "母亲通过父亲不通过";
                break;
            case "4":
                msg = "不通过";
                break;
            case "9":
                msg = "没有在金华户籍和房产，不比对";
        }
        UpdateWrapper<EduStudentEnrollPre> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(EduStudentEnrollPre::getStudentEnrollPreId, eduStuEnrollPre.getStudentEnrollPreId())
                .set(EduStudentEnrollPre::getFamilyFlag, infoComparison)
                .set(EduStudentEnrollPre::getFamilyRemark, msg);
        eduStudentEnrollPreService.update(updateWrapper);

        return infoComparison;
    }

    @Override
    @OpApi(funcCode = "F3307000010", title = "金华批量生成预报名数据", funcType = FuncTypeEnum.insert, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void createBatch(BatchCreateVO vo) {
        createBatchPageInfo(vo);
    }

    private String getStuFamInfoComparison(EduStudentEnrollPre eduStuEnrollPre) {
        CszmQueryVO cszmQueryVO = new CszmQueryVO();

        Boolean haveFatherIDFlag = StringUtils.isNotBlank(eduStuEnrollPre.getFatherIdcard());
        Boolean haveMotherIDFlag = StringUtils.isNotBlank(eduStuEnrollPre.getMotherIdcard());
        Boolean haveStuNameFlag = StringUtils.isNotBlank(eduStuEnrollPre.getFullName());

        if (haveStuNameFlag) {
            cszmQueryVO.setXm(eduStuEnrollPre.getFullName().trim());
        } else {
            throw new AppException("学生姓名不能为空！");
        }
        if (!haveFatherIDFlag && !haveMotherIDFlag) {
            throw new AppException("父亲或母亲身份证至少存在一个，不可全为空！");
        }
        //比对孩子是否在父母中一个的户口本下
        Boolean faFlag = false;
        Boolean moFlag = false;
        String infoComparison="4";
        LambdaQueryWrapper<EduHousehold> householdLambdaQueryWrapper = new LambdaQueryWrapper<>();
        householdLambdaQueryWrapper.select(EduHousehold::getHh,EduHousehold::getRelation,EduHousehold::getIdcard,EduHousehold::getFullName).eq(EduHousehold::getYear, eduStuEnrollPre.getYear())
                .eq(EduHousehold::getIdcard, eduStuEnrollPre.getIdcard())
                .eq(EduHousehold::getAuthStatus, AuthStatusEnum.YES.getType())
                .eq(EduHousehold::getStatus, BoolEnum.TRUE.getType());
        EduHousehold child = eduHouseholdService.getOne(householdLambdaQueryWrapper, false);
        //判断房产是否存在
        List<String> allIdcardList=new ArrayList<>();
        allIdcardList.add(eduStuEnrollPre.getIdcard());
        if(StringUtils.isNotBlank(eduStuEnrollPre.getMotherIdcard())){
            allIdcardList.add(eduStuEnrollPre.getMotherIdcard());
        }
        if(StringUtils.isNotBlank(eduStuEnrollPre.getFatherIdcard())){
            allIdcardList.add(eduStuEnrollPre.getFatherIdcard());
        }
        QueryWrapper<EduHouseDetail> oldDetailQueryWrapper = new QueryWrapper<>();
        oldDetailQueryWrapper
                .lambda()
                .select(EduHouseDetail::getHouseId,EduHouseDetail::getIdcard,EduHouseDetail::getFullName)
                .in(EduHouseDetail::getIdcard, allIdcardList)
                .eq(EduHouseDetail::getYear, eduStuEnrollPre.getYear());
        List<EduHouseDetail> houseDetailList=eduHouseDetailService.list(oldDetailQueryWrapper);
        Map<String, List<EduHouseDetail>> houseGroupBy = new HashMap<>();
        if(!CollectionUtils.isEmpty(houseDetailList)) {
            houseGroupBy=houseDetailList.stream().collect(Collectors.groupingBy(EduHouseDetail::getHouseId));
        }
        List<String> znxxList=new ArrayList<>();
        znxxList.add("子");
        znxxList.add("女");
        znxxList.add("长子");
        znxxList.add("长女");
        znxxList.add("一子");
        znxxList.add("次子");
        znxxList.add("一女");
        znxxList.add("次女");
        znxxList.add("二子");
        znxxList.add("三子");
        znxxList.add("四子");
        znxxList.add("五子");
        znxxList.add("六子");
        znxxList.add("七子");
        znxxList.add("八子");
        znxxList.add("九子");
        znxxList.add("十子");
        znxxList.add("二女");
        znxxList.add("三女");
        znxxList.add("四女");
        znxxList.add("五女");
        znxxList.add("六女");
        znxxList.add("七女");
        znxxList.add("八女");
        znxxList.add("九女");
        znxxList.add("十女");
        znxxList.add("其他儿子");
        znxxList.add("其他女儿");
        znxxList.add("孩子");
        znxxList.add("独生子");
        znxxList.add("独生女");
        znxxList.add("养女或继女");
        znxxList.add("养子或继子");
        if (child != null) {
            if(znxxList.contains(child.getRelation())){
                //与户主的关系是子或者女的才比对关系
                LambdaQueryWrapper<EduHousehold> fmLambdaQueryWrapper = new LambdaQueryWrapper<>();
                fmLambdaQueryWrapper.select(EduHousehold::getIdcard).eq(EduHousehold::getYear, eduStuEnrollPre.getYear())
                        .eq(EduHousehold::getHh, child.getHh())
                        .eq(EduHousehold::getAuthStatus, AuthStatusEnum.YES.getType())
                        .eq(EduHousehold::getStatus, BoolEnum.TRUE.getType());
                List<EduHousehold> hkList = eduHouseholdService.list(fmLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(hkList)) {
                    for (EduHousehold hk : hkList) {
                        if (StringUtils.isNotBlank(hk.getIdcard())) {
                            if (StringUtils.isNotBlank(eduStuEnrollPre.getFatherIdcard()) && eduStuEnrollPre.getFatherIdcard().equalsIgnoreCase(hk.getIdcard())) {
                                faFlag = true;
                            }
                            if (StringUtils.isNotBlank(eduStuEnrollPre.getMotherIdcard()) && eduStuEnrollPre.getMotherIdcard().equalsIgnoreCase(hk.getIdcard())) {
                                moFlag = true;
                            }
                        }
                    }
                }
            }

        }else{
            if (CollectionUtils.isEmpty(houseDetailList)) {
                //已同步没有户籍和没有房产的，不必对
                return "9";
            }
        }

        //父母和孩子都在同一个户口本
        if (faFlag&&moFlag) {
            return "1";
        }
        if(faFlag||moFlag){
            //一个比对通过的情况下，通过公安的数据比对一次
            LambdaQueryWrapper<EduHouseholdGa> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(EduHouseholdGa::getIdcard,eduStuEnrollPre.getIdcard()).eq(EduHouseholdGa::getYear,eduStuEnrollPre.getYear());
            EduHouseholdGa eduHouseholdGa=eduHouseholdGaService.getOne(lambdaQueryWrapper,false);
            if(eduHouseholdGa!=null){
                if(StringUtils.isNotBlank(eduHouseholdGa.getFatherIdcard())){
                    if (StringUtils.isNotBlank(eduStuEnrollPre.getFatherIdcard())){
                        if(eduHouseholdGa.getFatherIdcard().equalsIgnoreCase(eduStuEnrollPre.getFatherIdcard())){
                            faFlag=true;
                        }
                    }
                }
                if(StringUtils.isNotBlank(eduHouseholdGa.getMotherIdcard())){
                    if (StringUtils.isNotBlank(eduStuEnrollPre.getMotherIdcard())){
                        if(eduHouseholdGa.getMotherIdcard().equalsIgnoreCase(eduStuEnrollPre.getMotherIdcard())){
                            moFlag=true;
                        }
                    }
                }
                if(StringUtils.isNotBlank(eduHouseholdGa.getType1Idcard())){
                    if (StringUtils.isNotBlank(eduStuEnrollPre.getFatherIdcard())){
                        if(eduHouseholdGa.getType1Idcard().equalsIgnoreCase(eduStuEnrollPre.getFatherIdcard())){
                            faFlag=true;
                        }
                    }

                    if (StringUtils.isNotBlank(eduStuEnrollPre.getMotherIdcard())){
                        if(eduHouseholdGa.getType1Idcard().equalsIgnoreCase(eduStuEnrollPre.getMotherIdcard())){
                            moFlag=true;
                        }
                    }

                }
                if(StringUtils.isNotBlank(eduHouseholdGa.getType2Idcard())){
                    if (StringUtils.isNotBlank(eduStuEnrollPre.getFatherIdcard())){
                        if(eduHouseholdGa.getType1Idcard().equalsIgnoreCase(eduStuEnrollPre.getFatherIdcard())){
                            faFlag=true;
                        }
                    }

                    if (StringUtils.isNotBlank(eduStuEnrollPre.getMotherIdcard())){
                        if(eduHouseholdGa.getType1Idcard().equalsIgnoreCase(eduStuEnrollPre.getMotherIdcard())){
                            moFlag=true;
                        }
                    }

                }
            }
        }
        if (faFlag&&moFlag) {
            return "1";
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("cszm_batch_flag");
        commonVO.setAreaCode(areaCode);
        String cszmFlag = commonIntegration.getValueByKeyAndArea(commonVO);
        if(StringUtils.isBlank(cszmFlag)){
            cszmFlag="0";
        }

        if(faFlag&&!moFlag){
            if(haveMotherIDFlag){
                //先判断是否同房产证
                if (!CollectionUtils.isEmpty(houseGroupBy)) {
                    for(String houseId:houseGroupBy.keySet()){
                        List<EduHouseDetail> details=houseGroupBy.get(houseId);
                        boolean fatherFlag=false;
                        boolean motherFlag=false;
                        for(EduHouseDetail detail:details){
                            if (StringUtils.isNotBlank(detail.getIdcard())){
                                if (detail.getIdcard().equalsIgnoreCase(eduStuEnrollPre.getFatherIdcard())){
                                    fatherFlag=true;
                                }
                                if (detail.getIdcard().equalsIgnoreCase(eduStuEnrollPre.getMotherIdcard())){
                                    motherFlag=true;
                                }
                            }else{
                                if(StringUtils.isNotBlank(detail.getFullName())){
                                    if (detail.getFullName().equalsIgnoreCase(eduStuEnrollPre.getFatherName())){
                                        fatherFlag=true;
                                    }
                                    if (detail.getFullName().equalsIgnoreCase(eduStuEnrollPre.getFatherName())){
                                        motherFlag=true;
                                    }
                                }
                            }
                        }
                        if(fatherFlag&&motherFlag){
                            infoComparison="1";
                            break;
                        }
                    }
                    if(infoComparison.equalsIgnoreCase("1")){
                        return "1";
                    }
                }


                return "2";
            }else{
                return "1";
            }

        }else if(!faFlag&&moFlag){
            if(haveFatherIDFlag){
                //先判断是否同房产证
                if (!CollectionUtils.isEmpty(houseGroupBy)) {
                    for(String houseId:houseGroupBy.keySet()){
                        List<EduHouseDetail> details=houseGroupBy.get(houseId);
                        boolean fatherFlag=false;
                        boolean motherFlag=false;
                        for(EduHouseDetail detail:details){
                            if (StringUtils.isNotBlank(detail.getIdcard())){
                                if (detail.getIdcard().equalsIgnoreCase(eduStuEnrollPre.getFatherIdcard())){
                                    fatherFlag=true;
                                }
                                if (detail.getIdcard().equalsIgnoreCase(eduStuEnrollPre.getMotherIdcard())){
                                    motherFlag=true;
                                }
                            }else{
                                if(StringUtils.isNotBlank(detail.getFullName())){
                                    if (detail.getFullName().equalsIgnoreCase(eduStuEnrollPre.getFatherName())){
                                        fatherFlag=true;
                                    }
                                    if (detail.getFullName().equalsIgnoreCase(eduStuEnrollPre.getFatherName())){
                                        motherFlag=true;
                                    }
                                }
                            }
                        }
                        if(fatherFlag&&motherFlag){
                            infoComparison="1";
                            break;
                        }
                    }
                    if(infoComparison.equalsIgnoreCase("1")){
                        return "1";
                    }
                }

                return "3";
            }else{
                return "1";
            }
        }else {
            //先判断是否同房产证
            if (!CollectionUtils.isEmpty(houseGroupBy)) {
                for (String houseId : houseGroupBy.keySet()) {
                    List<EduHouseDetail> details = houseGroupBy.get(houseId);
                    boolean fatherFlag = false;
                    boolean motherFlag = false;
                    boolean childFlag = false;
                    for (EduHouseDetail detail : details) {
                        if (StringUtils.isNotBlank(detail.getIdcard())) {
                            if (detail.getIdcard().equalsIgnoreCase(eduStuEnrollPre.getFatherIdcard())) {
                                fatherFlag = true;
                            }
                            if (detail.getIdcard().equalsIgnoreCase(eduStuEnrollPre.getMotherIdcard())) {
                                motherFlag = true;
                            }
                            if (detail.getIdcard().equalsIgnoreCase(eduStuEnrollPre.getIdcard())) {
                                childFlag = true;
                            }
                        } else {
                            if (StringUtils.isNotBlank(detail.getFullName())) {
                                if (detail.getFullName().equalsIgnoreCase(eduStuEnrollPre.getFatherName())) {
                                    fatherFlag = true;
                                }
                                if (detail.getFullName().equalsIgnoreCase(eduStuEnrollPre.getFatherName())) {
                                    motherFlag = true;
                                }
                                if (detail.getFullName().equalsIgnoreCase(eduStuEnrollPre.getFullName())) {
                                    childFlag = true;
                                }
                            }
                        }
                    }
                    if (fatherFlag && motherFlag && childFlag) {
                        infoComparison = "1";
                        break;
                    }
                }
                if (infoComparison.equalsIgnoreCase("1")) {
                    return "1";
                }
            }

        }
        return "4";
    }

    public String saveDict(String dictField, String dictValue, String accessToken) {
        if (ObjectUtils.isEmpty(dictValue)) {
            return dictValue;
        }
        DictQueryVO dictQueryVO = new DictQueryVO();
        dictQueryVO.setDictField(dictField);
        dictQueryVO.setDictValue(dictValue);
        String key = dictIntegration.getKey(dictQueryVO);
        if (!ObjectUtils.isEmpty(key)) {
            return key;
        } else {
            List<SelectVO> dictList = dictIntegration.getDictByDictField(dictQueryVO);
            int maxKey =
                    dictList.stream()
                            .mapToInt(item -> Integer.parseInt(item.getDictKey()))
                            .max()
                            .getAsInt();
            DictVO dictVO = Convert.convert(DictVO.class, dictList.get(0));
            dictVO.setSysId(null);
            dictVO.setDictKey(maxKey + 1 + "");
            dictVO.setDictValue(dictValue);
            dictVO.setAccessToken(accessToken);
            dictIntegration.add(dictVO);
            return dictVO.getDictKey();
        }
    }

    private List<EduCompanyVO> getQyInterface(String tyxydm, Integer year, Boolean replaceFlag) {
        return new ArrayList<>();
    }

    //批量生成，循环处理，每次500条
    private void createBatchPageInfo(BatchCreateVO vo) {

        if (StringUtils.isNotBlank(vo.getBeforeFlag()) && BoolEnum.TRUE.getType().equals(vo.getBeforeFlag())) {
            throw new AppException("成功数据不能重新比对");
        } else {
            if (vo.getPageNum() != null && vo.getPageNum() > 30) {
                return;
            }

        }
        //房产户籍都获取大数据的情况下才能进行预报名生成
        QueryWrapper<EduStudentEnrollPre> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduStudentEnrollPre::getAuthStatus, AuthStatusEnum.YES.getType())
                .eq(EduStudentEnrollPre::getHouseSyncFlag, BoolEnum.TRUE.getType())
                .eq(EduStudentEnrollPre::getHouseholdSyncFlag, BoolEnum.TRUE.getType());
        if (StringUtils.isBlank(vo.getBeforeFlag())) {
            queryWrapper.lambda().eq(EduStudentEnrollPre::getBeforeFlag, "0");
        } else {
            queryWrapper.lambda().eq(EduStudentEnrollPre::getBeforeFlag, vo.getBeforeFlag());
        }
        int pageNum = 1;
        int pageSize = 1000;
        PageHelper.startPage(pageNum, pageSize);
        List<EduStudentEnrollPre> list = eduStudentEnrollPreService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        PageInfo<EduStudentEnrollPre> prePageInfo = new PageInfo<>(list);
        for (EduStudentEnrollPre eduStudentEnrollPre : prePageInfo.getList()) {
            try {
                createBefore(eduStudentEnrollPre);
                eduEnrollClearCacheHelper.clearCachePreBefore(eduStudentEnrollPre.getStudentEnrollPreId());
            } catch (AppException e) {
                logger.error("批量生成预报名失败", e.getMessage());
            } catch (Exception e) {
                logger.error("批量生成预报名失败", e.getMessage());
            }
        }
        if (prePageInfo.isHasNextPage()) {
            vo.setPageNum(vo.getPageNum() == null ? 1 : vo.getPageNum() + 1);
            vo.setPageSize(pageSize);
            this.createBatchPageInfo(vo);

        }
    }

    public int createBefore(EduStudentEnrollPre eduStudentEnrollPre) {
        String beforeFlag = "0";
        String msg = "成功";
        int count = 0;
        boolean isIdcard = IdcardUtil.isValidCard(eduStudentEnrollPre.getIdcard());
        if (StringUtils.isBlank(eduStudentEnrollPre.getCardType())) {
            if (isIdcard) {
                eduStudentEnrollPre.setCardType(CardTypeEnum.idcard.getType());
            } else {
                eduStudentEnrollPre.setCardType("99");
            }
        }
        if (isIdcard) {
            if (eduStudentEnrollPre.getAge() == null) {
                eduStudentEnrollPre.setAge(IdcardUtil.getAgeByIdCard(eduStudentEnrollPre.getIdcard(), DateUtil.parse(eduStudentEnrollPre.getYear() + "0831", "yyyyMMdd")));
            }
            if (StringUtils.isBlank(eduStudentEnrollPre.getBirthYmd())) {
                eduStudentEnrollPre.setBirthYmd(IdcardUtil.getBirth(eduStudentEnrollPre.getIdcard()));
            }
            if (StringUtils.isBlank(eduStudentEnrollPre.getSex())) {
                int gender = IdcardUtil.getGenderByIdCard(eduStudentEnrollPre.getIdcard());
                if (gender == 1) {
                    // 男
                    eduStudentEnrollPre.setSex("1");
                } else {
                    // 女
                    eduStudentEnrollPre.setSex("2");
                }
            }
        } else {
            if (eduStudentEnrollPre.getAge() == null) {
                if (StringUtils.isNotBlank(eduStudentEnrollPre.getBirthYmd())) {
                    if (eduStudentEnrollPre.getBirthYmd().length() >= 8) {
                        eduStudentEnrollPre.setAge(DateUtil.age(DateUtil.parse(eduStudentEnrollPre.getBirthYmd().replaceAll("-", "").replaceAll("/", ""), "yyyyMMdd"), DateUtil.parse(eduStudentEnrollPre.getYear() + "0831", "yyyyMMdd")));
                    } else if (eduStudentEnrollPre.getBirthYmd().length() == 6) {
                        eduStudentEnrollPre.setAge(DateUtil.age(DateUtil.parse(eduStudentEnrollPre.getBirthYmd() + "01", "yyyyMMdd"), DateUtil.parse(eduStudentEnrollPre.getYear() + "0831", "yyyyMMdd")));
                    }

                }

            }
        }
        try {
            count = jhEnrollBeforeCreateHelper.createEnrollBefore(eduStudentEnrollPre);
            if (count > 0) {
                beforeFlag = "1";
            } else {
                beforeFlag = "3";
            }

        } catch (AppException e) {
            if(e.getCode()==100){
                beforeFlag = "0";
            }else{
                beforeFlag = "2";
            }
            logger.error("生成预报名失败："+e.getMsg());

            msg = e.getMsg();
            throw new AppException(e.getMsg());
        } catch (Exception e) {
            logger.error("生成预报名失败："+e.getMessage());
            beforeFlag = "2";
            msg = e.getMessage();
            throw new RuntimeException(e.getMessage());
        }
        if (msg.length() > 200) {
            msg = msg.substring(0, 200);
        }

        eduStudentEnrollPre.setBeforeFlag(beforeFlag);
        eduStudentEnrollPre.setBeforeRemark(msg);
        if (StringUtils.isNotBlank(eduStudentEnrollPre.getFullName())) {
            eduStudentEnrollPre.setFullName(eduStudentEnrollPre.getFullName().trim());
        }
        if (StringUtils.isNotBlank(eduStudentEnrollPre.getMotherName())) {
            eduStudentEnrollPre.setMotherName(eduStudentEnrollPre.getMotherName().trim());
        }
        if (StringUtils.isNotBlank(eduStudentEnrollPre.getFatherName())) {
            eduStudentEnrollPre.setFatherName(eduStudentEnrollPre.getFatherName().trim());
        }
        eduStudentEnrollPreService.updateById(eduStudentEnrollPre);
        return count;
    }

    //批量预测生成，循环处理，每次500条
    private void createCalculateBatchPageInfo(BatchCreateVO vo) {

        if (StringUtils.isNotBlank(vo.getCalculateFlag()) && BoolEnum.TRUE.getType().equals(vo.getCalculateFlag())) {
            throw new AppException("成功数据不能重新比对");
        } else {
            if (vo.getPageNum() != null && vo.getPageNum() > 30) {
                return;
            }
        }
        //房产户籍都获取大数据的情况下才能进行预报名生成
        QueryWrapper<EduStudentEnrollPre> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduStudentEnrollPre::getAuthStatus, AuthStatusEnum.YES.getType())
                .eq(EduStudentEnrollPre::getHouseSyncFlag, BoolEnum.TRUE.getType())
                .eq(EduStudentEnrollPre::getHouseholdSyncFlag, BoolEnum.TRUE.getType());
        if (StringUtils.isBlank(vo.getCalculateFlag())) {
            queryWrapper.lambda().eq(EduStudentEnrollPre::getCalculateFlag, "0");
        } else {
            queryWrapper.lambda().eq(EduStudentEnrollPre::getCalculateFlag, vo.getCalculateFlag());
        }
        int pageNum = 1;
        int pageSize = 1000;
        PageHelper.startPage(pageNum, pageSize);
        List<EduStudentEnrollPre> list = eduStudentEnrollPreService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        PageInfo<EduStudentEnrollPre> prePageInfo = new PageInfo<>(list);
        for (EduStudentEnrollPre eduStudentEnrollPre : prePageInfo.getList()) {
            createCalculate(eduStudentEnrollPre);
        }
        if (prePageInfo.isHasNextPage()) {
            vo.setPageNum(vo.getPageNum() == null ? 1 : vo.getPageNum() + 1);
            vo.setPageSize(pageSize);
            this.createCalculateBatchPageInfo(vo);

        }
    }

    public int createCalculate(EduStudentEnrollPre eduStudentEnrollPre) {
        String beforeFlag = "0";
        String msg = "成功";
        int count = 0;

        try {
            count = dyEnrollCalculateCreateHelper.createEnrollBefore(eduStudentEnrollPre);
            if (count > 0) {
                beforeFlag = "1";
            } else {
                beforeFlag = "3";
            }

        } catch (AppException e) {
            logger.error("生成预报名失败："+e.getMsg());
            beforeFlag = "2";
            msg = e.getMsg();
        } catch (Exception e) {
            logger.error("生成预报名失败："+e.getMessage());
            beforeFlag = "2";
            msg = e.getMessage();

        }
        if (msg.length() > 200) {
            msg = msg.substring(0, 200);
        }

        eduStudentEnrollPre.setCalculateFlag(beforeFlag);
        eduStudentEnrollPre.setCalculateRemark(msg);
        eduStudentEnrollPreService.updateById(eduStudentEnrollPre);
        return count;
    }

    @Override
    @OpApi(funcCode = "F3307000011", title = "大数据户籍接口信息获取", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduHouseholdVO> queryBigDataHousehold(HouseHoldSaveVO vo) {
        List<EduHouseholdVO> eduHouseholdVOList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getIdcard())) {
            return null;
        }

        try {

            JSONArray jsonArray = jhIrsIntegration.getFamilyInfoIrs(vo.getIdcard(),vo.getReqIp());
            if (jsonArray != null && jsonArray.size() > 0) {
                jsonArray.forEach(
                        item -> {
                            JSONObject personData = (JSONObject) item;
                            EduHouseHoldInterfaceVO holdInterfaceVO =
                                    personData
                                            .getJSONObject("ELC_LICENCE_STRUCT")
                                            .getObject("DATA", EduHouseHoldInterfaceVO.class);
                            String elcLicenceName = (String) personData.get("ELC_LICENCE_NAME");
                            holdInterfaceVO.setElcLicenceName(elcLicenceName);

                            EduHouseholdVO eduHousehold = new EduHouseholdVO();
                            eduHousehold.setHouseholdId(IdUtil.simpleUUID());
                            eduHousehold.setHhid(holdInterfaceVO.getCZRKHHID());
                            eduHousehold.setHh(holdInterfaceVO.getCZRKHH());
                            eduHousehold.setIdcard(holdInterfaceVO.getCZRKGMSFHM());
                            eduHousehold.setFullName(holdInterfaceVO.getCZRKXM());
                            eduHousehold.setAddress(holdInterfaceVO.getCZRKZZ());
                            eduHousehold.setBirthday(holdInterfaceVO.getCZRKCSRQ());
                            eduHousehold.setSex(holdInterfaceVO.getCZRKXB());
                            eduHousehold.setCountry(holdInterfaceVO.getCZRKJGGJ());
                            eduHousehold.setBirthplace(holdInterfaceVO.getCZRKCSDSSX());
                            eduHousehold.setNativePlace(holdInterfaceVO.getCZRKJGSSX());
                            eduHousehold.setHouseholdPlace(holdInterfaceVO.getCZRKZZ());
                            eduHousehold.setAccountType(holdInterfaceVO.getElcLicenceName());
                            eduHousehold.setRelation(holdInterfaceVO.getCZRKYHZGX());
                            eduHousehold.setHouseholder(holdInterfaceVO.getCZRKHZXM());
                            eduHousehold.setServiceSpaces(holdInterfaceVO.getCZRKFWCS());
                            eduHousehold.setHsqlbs(holdInterfaceVO.getCZRKHSQLBS());//何时迁来本市
                            eduHousehold.setHsqlbz(holdInterfaceVO.getCZRKHSQLBZ());//何时来本址
                            eduHousehold.setHssqlbz(holdInterfaceVO.getCZRKHZQLSSX());
                            eduHousehold.setHssqxqlws(holdInterfaceVO.getCZRKHDQLXZ());
                            eduHousehold.setHxzlbd(holdInterfaceVO.getCZRKHZQLXZ());

                            if (StringUtils.isNotBlank(holdInterfaceVO.getCZRKHSQLBZ())) {
                                try {
                                    if (holdInterfaceVO.getCZRKHSQLBZ().length() == 8) {
                                        eduHousehold.setRegistrationDate(DatePattern.PURE_DATE_FORMAT.parse(holdInterfaceVO.getCZRKHSQLBZ()));
                                    } else if (holdInterfaceVO.getCZRKHSQLBZ().length() == 10) {
                                        eduHousehold.setRegistrationDate(DatePattern.NORM_DATE_FORMAT.parse(holdInterfaceVO.getCZRKHSQLBZ()));
                                    }
                                } catch (Exception e) {
                                    logger.error("户籍迁入时间格式转换异常" + e.getMessage());
                                }

                            }
                            eduHouseholdVOList.add(eduHousehold);
                        });
            }
        } catch (Exception e) {
            throw new AppException(e.getMessage());
        }
        return eduHouseholdVOList;
    }

    @Override
    @OpApi(funcCode = "F3307000012", title = "大数据房产接口信息获取", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduHouseVO> queryBigDataHouseInterface(HouseInterfaceSaveVO vo) {
        List<EduHouseVO> eduHouseVOList = new ArrayList<>();
        try {

            JSONArray houseArr = new JSONArray();
            JSONArray houseStArr = jhIrsIntegration.getFcJh(vo.getName(), vo.getIdcard(),vo.getReqIp());
            if (houseStArr != null) {
                houseArr.addAll(houseStArr);
            }
            if (vo.getIdcard().indexOf("X") > 0) {
                JSONArray houseStArrX = jhIrsIntegration.getFcJh(vo.getName(), vo.getIdcard().toLowerCase(),vo.getReqIp());
                if (houseStArrX != null) {
                    houseArr.addAll(houseStArrX);
                }
            }

            if (houseArr.size() > 0) {
                List<Map<String, String>> hasList = new ArrayList<>();
                List<String> hasBdcdyhList = new ArrayList<>();
                for (Object item : houseArr) {
                    HouseInterfaceVO house = Convert.convert(HouseInterfaceVO.class, item);
                    String realProperty = house.getQlrxxList().stream()
                            .map(HouseInterfaceDetailVO::getBdcqzh)
                            .distinct()
                            .collect(Collectors.joining(","));

                    if (!ObjectUtils.isEmpty(house.getBdcdyh())) {
                        if (hasBdcdyhList.contains(house.getBdcdyh())) {
                            continue;
                        }
                        hasBdcdyhList.add(house.getBdcdyh());
                    } else {
                        Map<String, String> realMap = new HashMap<>();
                        realMap.put("realProperty", realProperty);
                        realMap.put("zl", house.getZl());
                        boolean continueFlg = false;
                        for (Map<String, String> map : hasList) {
                            if (map.get("realProperty").equals(realProperty) && map.get("zl").equals(house.getZl())) {
                                continueFlg = true;
                                break;
                            }
                        }
                        if (continueFlg) {
                            continue;
                        }
                        hasList.add(realMap);
                    }

                    List<String> qlrList = new ArrayList<>();
                    String qlrName = "";
                    List<String> qlrNameList = new ArrayList<>();
                    for (HouseInterfaceDetailVO detailVO : house.getQlrxxList()) {
                        if (StringUtils.isBlank(detailVO.getZjh())) {
                        } else {
                            if (IdcardUtil.isValidCard(detailVO.getZjh())) {
                                if (detailVO.getZjh().length() == 15) {
                                    qlrList.add(IdcardUtil.convert15To18(detailVO.getZjh().toUpperCase()));
                                } else {
                                    qlrList.add(detailVO.getZjh().toUpperCase());
                                }
                            } else {
                                qlrList.add(detailVO.getZjh().toUpperCase());
                            }


                        }
                        qlrNameList.add(detailVO.getQlr());
                        if (StringUtils.isBlank(qlrName)) {
                            qlrName = detailVO.getQlr() + "(" + detailVO.getZjh() + ")";
                        } else {
                            qlrName = qlrName + "," + detailVO.getQlr() + "(" + detailVO.getZjh() + ")";
                        }
                    }
                    EduHouse eduHouse = new EduHouse();
                    eduHouse.setHouseId(IdUtil.simpleUUID());
                    eduHouse.setAddress(house.getZl());
                    if (!ObjectUtils.isEmpty(house.getDjsj())) {
                        eduHouse.setRegisterDate(
                                DateUtil.parse(house.getDjsj(), "yyyy年MM月dd日"));
                    }
                    if (!ObjectUtils.isEmpty(house.getQlrxxList())) {
                        eduHouse.setRealProperty(realProperty);
                    }
                    eduHouse.setRealPropertyNum(house.getBdcdyh());
                    if (!ObjectUtils.isEmpty(house.getTdsyqssj())) {
                        eduHouse.setBegDate(
                                DateUtil.parse(house.getTdsyqssj(), "yyyy年MM月dd日"));
                    }
                    if (!ObjectUtils.isEmpty(house.getTdsyjssj())) {
                        eduHouse.setEndDate(
                                DateUtil.parse(house.getTdsyjssj(), "yyyy年MM月dd日"));
                    }
                    String yt = house.getYt().replace("/", "").trim();
                    eduHouse.setLandCategories(
                            saveDict("LANDCATEGORIES", yt, vo.getAccessToken()));
                    eduHouse.setLandCategoriesName(yt);
                    eduHouse.setHouseNature(
                            saveDict("HOUSENATURE", house.getFwxz(), vo.getAccessToken()));
                    eduHouse.setHouseNatureName(house.getFwxz());
//                    eduHouse.setStatus("1");
//                    eduHouse.setAuthStatus(AuthStatusEnum.NODO.getType());
                    if (!ObjectUtils.isEmpty(house.getQlrxxList())) {
                        List<HouseInterfaceDetailVO> qlrxxList = house.getQlrxxList();
                        if (!ObjectUtils.isEmpty(house.getTdsyjssj())
                                && !ObjectUtils.isEmpty(house.getTdsyqssj())) {
                            int betweenYear =
                                    (int)
                                            DateUtil.betweenYear(
                                                    DateUtil.offsetDay(
                                                            DateUtil.parse(
                                                                    house.getTdsyqssj(),
                                                                    "yyyy年MM月dd日"),
                                                            -1),
                                                    DateUtil.parse(
                                                            house.getTdsyjssj(),
                                                            "yyyy年MM月dd日"),
                                                    false);
                            eduHouse.setYearLimit(betweenYear);
                        } else {
                            eduHouse.setYearLimit(100);
                        }
                        eduHouse.setQlrNum(qlrxxList.size());
                        eduHouse.setQlrName(qlrName);
                    }
                    eduHouseVOList.add(Convert.convert(EduHouseVO.class, eduHouse));
                }
            }
        } catch (Exception e) {
            logger.error("房产获取异常"+e.getMessage());
            throw new AppException(e.getMessage());
        }
        return eduHouseVOList;
    }

    @Override
    @OpApi(funcCode = "F3307000014", title = "义务段家长端报名保存", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void saveEnroll(SaveStudentEnrollVO vo) {
        String applyId = jhEnrollHelper.save(vo);
        vo.setApplyId(applyId);
    }

    @Override
    @OpApi(funcCode = "F3307000023", title = "义务段模拟报名保存", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void saveImitateEnroll(SaveStudentEnrollVO vo) {
        String applyId = jhImitateEnrollHelper.save(vo);
        vo.setApplyId(applyId);
    }

    //录取报名数据
    @Override
    @OpApi(funcCode = "F3307000015", title = "录取报名数据", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void unifiedSupervisionEnrollAdmit(EduJhjySync eduJhjySync) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhjy_sync_url");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("金华教育监管平台接口地址参数未配置！(jhjy_sync_url)");
        }
        if (StringUtils.isBlank(eduJhjySync.getIdcard())) {
            throw new AppException("身份证不能为空");
        }
        if (eduJhjySync.getEduStage() == null) {
            throw new AppException("学段不能为空");
        }
        if (eduJhjySync.getSchoolType() == null) {
            throw new AppException("学校类型不能为空");
        }
        if (StringUtils.isBlank(eduJhjySync.getSchoolName())) {
            throw new AppException("学校名称不能为空");
        }
        url = url + "/OpenAPI/UnifiedSupervisionEnrollAdmit";
        JhjyLqVO jhjyLqVO = Convert.convert(JhjyLqVO.class, eduJhjySync);
        String body = JSON.toJSONString(jhjyLqVO);
        String request = getRequest(body);
        String retBody = send(url, request);
        if (StringUtils.isBlank(retBody)) {
            throw new AppException("金华教育录取上传接口，未返回信息");
        }
        JhjyRetVO retVO = null;
        try {
            retVO = JSON.parseObject(retBody, JhjyRetVO.class);
        } catch (Exception e) {
            throw new AppException("金华教育录取上传接口失败：" + body);
        }
        if (!"200".equals(retVO.getResult_code())) {
            throw new AppException(retVO.getMsg());
        }

    }

    //录取报名数据
    @Override
    @OpApi(funcCode = "F3307000016", title = "查询录取情况", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public String unifiedSupervisionEnrollSearchAdmit(JhjyQueryVO vo) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhjy_sync_url");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("金华教育监管平台接口地址参数未配置！(jhjy_sync_url)");
        }
        if (StringUtils.isBlank(vo.getIdcard())) {
            throw new AppException("查询的身份证不能为空");
        }
        if (vo.getEduStage() == null) {
            throw new AppException("查询的学段不能为空");
        }
        url = url + "/OpenAPI/UnifiedSupervisionEnrollSearchAdmit";
        String body = JSON.toJSONString(vo);
        String request = getRequest(body);
        String retBody = send(url, request);
        if (StringUtils.isBlank(retBody)) {
            throw new AppException("金华教育查询上传接口，未返回信息");
        }
        JhjyRetVO retVO = null;
        try {
            retVO = JSON.parseObject(retBody, JhjyRetVO.class);
        } catch (Exception e) {
            throw new AppException("金华教育查询接口失败：" + body);
        }
        if (!"200".equals(retVO.getResult_code())) {
            throw new AppException(retVO.getMsg());
        }
        Object obj = retVO.getData();
        return obj.toString();

    }


    //录取报名数据
    @Override
    @OpApi(funcCode = "F3307000020", title = "报名数据上传", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void unifiedSupervisionEnrollAdd(EduJhjySync eduJhjySync) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhjy_sync_url");
        commonVO.setAreaCode(areaCode);
        String url= commonIntegration.getValueByKeyAndArea(commonVO);
        if(StringUtils.isBlank(url)){
            throw new AppException("金华教育监管平台接口地址参数未配置！(jhjy_sync_url)");
        }
        if(StringUtils.isBlank(eduJhjySync.getIdcard())){
            throw new AppException("身份证不能为空");
        }
        if(eduJhjySync.getEduStage()==null){
            throw new AppException("学段不能为空");
        }
        if(eduJhjySync.getSchoolType()==null){
            throw new AppException("学校类型不能为空");
        }
        if(StringUtils.isBlank(eduJhjySync.getSchoolName())){
            throw new AppException("学校名称不能为空");
        }
        url=url+"/OpenAPI/UnifiedSupervisionEnrollAdd";
        JhjyBmVO jhjyBmVO= Convert.convert(JhjyBmVO.class,eduJhjySync);
        String body= JSON.toJSONString(jhjyBmVO);
        String request=getRequest(body);
        String retBody=send(url,request);
        if (StringUtils.isBlank(retBody)) {
            throw new AppException("金华教育报名上传接口，未返回信息");
        }
        JhjyRetVO retVO=null;
        try{
            retVO= JSON.parseObject(retBody,JhjyRetVO.class);
        }catch (Exception e){
            throw new AppException("金华教育报名上传接口失败：" + body);
        }
        if(!"200".equals(retVO.getResult_code())){
            throw new AppException(retVO.getMsg());
        }

    }

    //录取报名数据
    @Override
    @OpApi(funcCode = "F3307000021", title = "报名数据删除", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void unifiedSupervisionEnrollDelete(EduJhjySync eduJhjySync) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhjy_sync_url");
        commonVO.setAreaCode(areaCode);
        String url= commonIntegration.getValueByKeyAndArea(commonVO);
        if(StringUtils.isBlank(url)){
            throw new AppException("金华教育监管平台接口地址参数未配置！(jhjy_sync_url)");
        }
        if(StringUtils.isBlank(eduJhjySync.getIdcard())){
            throw new AppException("身份证不能为空");
        }
        if(eduJhjySync.getEduStage()==null){
            throw new AppException("学段不能为空");
        }
        if(StringUtils.isBlank(eduJhjySync.getDeleteReason())){
            throw new AppException("删除理由不能为空");
        }
        url=url+"/OpenAPI/UnifiedSupervisionEnrollDelete";
        JhjyQxbmVO jhjyQxbmVO= Convert.convert(JhjyQxbmVO.class,eduJhjySync);
        String body= JSON.toJSONString(jhjyQxbmVO);
        String request=getRequest(body);
        String retBody=send(url,request);
        if (StringUtils.isBlank(retBody)) {
            throw new AppException("金华教育取消报名上传接口，未返回信息");
        }
        JhjyRetVO retVO=null;
        try{
            retVO=JSON.parseObject(retBody,JhjyRetVO.class);
        }catch (Exception e){
            throw new AppException("金华教育取消报名上传接口失败：" + body);
        }
        if(!"200".equals(retVO.getResult_code())){
            throw new AppException(retVO.getMsg());
        }
    }

    //录取报名数据
    @Override
    @OpApi(funcCode = "F3307000022", title = "取消录取报名数据", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public void unifiedSupervisionEnrollCancelAdmit(EduJhjySync eduJhjySync) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhjy_sync_url");
        commonVO.setAreaCode(areaCode);
        String url= commonIntegration.getValueByKeyAndArea(commonVO);
        if(StringUtils.isBlank(url)){
            throw new AppException("金华教育监管平台接口地址参数未配置！(jhjy_sync_url)");
        }
        if(StringUtils.isBlank(eduJhjySync.getIdcard())){
            throw new AppException("身份证不能为空");
        }
        if(eduJhjySync.getEduStage()==null){
            throw new AppException("学段不能为空");
        }
        url=url+"/OpenAPI/UnifiedSupervisionEnrollCancelAdmit";
        JhjyQxlqVO jhjyQxlqVO= Convert.convert(JhjyQxlqVO.class,eduJhjySync);
        String body= JSON.toJSONString(jhjyQxlqVO);
        String request=getRequest(body);
        String retBody=send(url,request);
        if (StringUtils.isBlank(retBody)) {
            throw new AppException("金华教育取消录取上传接口，未返回信息");
        }
        JhjyRetVO retVO=null;
        try{
            retVO= JSON.parseObject(retBody,JhjyRetVO.class);
        }catch (Exception e){
            throw new AppException("金华教育取消录取上传接口失败：" + body);
        }
        if(!"200".equals(retVO.getResult_code())){
            throw new AppException(retVO.getMsg());
        }
    }

    //获取请求体
    private String getRequest(String body) {
        if (StringUtils.isBlank(body)) {
            throw new AppException("调用金华教育接口请求体不能为空");
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhjy_sync_jmsy");
        commonVO.setAreaCode(areaCode);
        String PRIVATE_KEY = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(PRIVATE_KEY)) {
            throw new AppException("金华教育监管平台接口加密私钥参数未配置！(jhjy_sync_jmsy)");
        }
        RSA rsa_de = new RSA(PRIVATE_KEY, null);
        byte[] encrypt = rsa_de.encrypt(body, KeyType.PrivateKey);
        return Base64.encode(encrypt);
    }

    //发送信息
    private String send(String url, String request) {
        Map<String, Object> map = new HashMap<>();
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhjy_sync_app_key");
        commonVO.setAreaCode(areaCode);
        String appKey = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(appKey)) {
            throw new AppException("金华教育监管平台接口参数未配置！(jhjy_sync_app_key)");
        }
        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("jhjy_sync_app_secret");
        commonVO2.setAreaCode(areaCode);
        String appSecret = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(appSecret)) {
            throw new AppException("金华教育监管平台接口参数未配置！(jhjy_sync_app_secret)");
        }
        map.put("appKey", appKey);
        map.put("request", request);
        String sign = SecureUtil.md5(request + appSecret);
        map.put("sign", sign);
        String ret = HttpRequest.post(url)
                .form(map)//表单内容
                .timeout(10000)//超时，毫秒
                .execute().body();
        return ret;

    }

    @Override
    @OpApi(funcCode = "F3307000017", title = "大数据企业接口信息获取", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduCompanyVO> queryQyInterfaceData(QySearchVO vo) {
        return new ArrayList<>();
    }

    @Override
    @OpApi(funcCode = "F3307000018", title = "特殊通道人员维护房产大数据获取", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduHouseVO> queryEnrollBeforeHouse(HouseInterfaceSaveVO vo) {
        List<EduHouseVO> eduHouseVOList = new ArrayList<>();
        try {

            JSONArray houseArr = new JSONArray();
            JSONArray houseStArr = jhIrsIntegration.getFcJh(vo.getName(), vo.getIdcard(),vo.getReqIp());
            if (houseStArr != null) {
                houseArr.addAll(houseStArr);
            }
            if (vo.getIdcard().indexOf("X") > 0) {
                JSONArray houseStArrX = jhIrsIntegration.getFcJh(vo.getName(), vo.getIdcard().toLowerCase(),vo.getReqIp());
                if (houseStArrX != null) {
                    houseArr.addAll(houseStArrX);
                }
            }

            if (houseArr.size() > 0) {
                List<Map<String, String>> hasList = new ArrayList<>();
                List<String> hasBdcdyhList = new ArrayList<>();
                for (Object item : houseArr) {
                    HouseInterfaceVO house = Convert.convert(HouseInterfaceVO.class, item);
                    String realProperty = house.getQlrxxList().stream()
                            .map(HouseInterfaceDetailVO::getBdcqzh)
                            .distinct()
                            .collect(Collectors.joining(","));

                    if (!ObjectUtils.isEmpty(house.getBdcdyh())) {
                        if (hasBdcdyhList.contains(house.getBdcdyh())) {
                            continue;
                        }
                        hasBdcdyhList.add(house.getBdcdyh());
                    } else {
                        Map<String, String> realMap = new HashMap<>();
                        realMap.put("realProperty", realProperty);
                        realMap.put("zl", house.getZl());
                        boolean continueFlg = false;
                        for (Map<String, String> map : hasList) {
                            if (map.get("realProperty").equals(realProperty) && map.get("zl").equals(house.getZl())) {
                                continueFlg = true;
                                break;
                            }
                        }
                        if (continueFlg) {
                            continue;
                        }
                        hasList.add(realMap);
                    }

                    List<String> qlrList = new ArrayList<>();
                    String qlrName = "";
                    List<String> qlrNameList = new ArrayList<>();
                    for (HouseInterfaceDetailVO detailVO : house.getQlrxxList()) {
                        if (StringUtils.isBlank(detailVO.getZjh())) {
                        } else {

                            if (IdcardUtil.isValidCard(detailVO.getZjh())) {
                                if (detailVO.getZjh().length() == 15) {
                                    qlrList.add(IdcardUtil.convert15To18(detailVO.getZjh().toUpperCase()));
                                } else {
                                    qlrList.add(detailVO.getZjh().toUpperCase());
                                }
                            } else {
                                qlrList.add(detailVO.getZjh().toUpperCase());
                            }

                        }
                        qlrNameList.add(detailVO.getQlr());
                        if (StringUtils.isBlank(qlrName)) {
                            qlrName = detailVO.getQlr() + "(" + detailVO.getZjh() + ")";
                        } else {
                            qlrName = qlrName + "," + detailVO.getQlr() + "(" + detailVO.getZjh() + ")";
                        }
                    }
                    EduHouse eduHouse = new EduHouse();
                    // eduHouse.setHouseId(IdUtil.simpleUUID());
                    eduHouse.setAddress(house.getZl());
                    if (!ObjectUtils.isEmpty(house.getDjsj())) {
                        eduHouse.setRegisterDate(
                                DateUtil.parse(house.getDjsj(), "yyyy年MM月dd日"));
                    }
                    if (!ObjectUtils.isEmpty(house.getQlrxxList())) {
                        eduHouse.setRealProperty(realProperty);
                    }
                    eduHouse.setRealPropertyNum(house.getBdcdyh());
                    if (!ObjectUtils.isEmpty(house.getTdsyqssj())) {
                        eduHouse.setBegDate(
                                DateUtil.parse(house.getTdsyqssj(), "yyyy年MM月dd日"));
                    }
                    if (!ObjectUtils.isEmpty(house.getTdsyjssj())) {
                        eduHouse.setEndDate(
                                DateUtil.parse(house.getTdsyjssj(), "yyyy年MM月dd日"));
                    }
                    String yt = house.getYt().replace("/", "").trim();
                    eduHouse.setLandCategories(
                            saveDict("LANDCATEGORIES", yt, vo.getAccessToken()));
                    eduHouse.setLandCategoriesName(yt);
                    eduHouse.setHouseNature(
                            saveDict("HOUSENATURE", house.getFwxz(), vo.getAccessToken()));
                    eduHouse.setHouseNatureName(house.getFwxz());
//                    eduHouse.setStatus("1");
//                    eduHouse.setAuthStatus(AuthStatusEnum.NODO.getType());
                    if (!ObjectUtils.isEmpty(house.getQlrxxList())) {
                        List<HouseInterfaceDetailVO> qlrxxList = house.getQlrxxList();
                        if (!ObjectUtils.isEmpty(house.getTdsyjssj())
                                && !ObjectUtils.isEmpty(house.getTdsyqssj())) {
                            int betweenYear =
                                    (int)
                                            DateUtil.betweenYear(
                                                    DateUtil.offsetDay(
                                                            DateUtil.parse(
                                                                    house.getTdsyqssj(),
                                                                    "yyyy年MM月dd日"),
                                                            -1),
                                                    DateUtil.parse(
                                                            house.getTdsyjssj(),
                                                            "yyyy年MM月dd日"),
                                                    false);
                            eduHouse.setYearLimit(betweenYear);
                        } else {
                            eduHouse.setYearLimit(100);
                        }
                        eduHouse.setQlrNum(qlrxxList.size());
                        eduHouse.setQlrName(qlrName);
                    }
                    EduHouseVO eduHouseVO = Convert.convert(EduHouseVO.class,eduHouse);
                    eduHouseVO.setHouseInterfaceVO(house);
                    eduHouseVOList.add(eduHouseVO);
                }
            }
        } catch (Exception e) {
            logger.error("房产获取异常"+e.getMessage());
            throw new AppException(e.getMessage());
        }
        return eduHouseVOList;
    }

    @Override
    @OpApi(funcCode = "F3307000019", title = "东阳幼儿园房产接口信息获取并保存", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE, savelog = false)
    public List<EduHouseVO> saveHouseNurseryInterfaceData(HouseInterfaceSaveVO vo) {
        List<EduHouseVO> eduHouseVOList = new ArrayList<>();
        try {
            int year = 0;
            year = eduHelper.thisYear();
            QueryWrapper<EduHouseDetailNursery> oldDetailQueryWrapper = new QueryWrapper<>();
            oldDetailQueryWrapper
                    .lambda()
                    .eq(EduHouseDetailNursery::getIdcard, vo.getIdcard())
                    .eq(EduHouseDetailNursery::getFullName, vo.getName())
                    .eq(EduHouseDetailNursery::getYear, year)
                    .select(EduHouseDetailNursery::getHouseId);
            List<String> houseIdList =
                    eduHouseDetailNurseryService.list(oldDetailQueryWrapper).stream()
                            .map(EduHouseDetailNursery::getHouseId)
                            .collect(Collectors.toList());
            if (houseIdList.size() > 0) {
                eduHouseDetailNurseryService.removeByIds(houseIdList);
                eduHouseNurseryService.removeByIds(houseIdList);
            }
            JSONArray houseArr = jhIrsIntegration.getFcJh(vo.getName(), vo.getIdcard(),vo.getReqIp());
            if (houseArr.size() > 0) {
                int finalYear = year;
                houseArr.forEach(
                        item -> {
                            HouseInterfaceVO house = Convert.convert(HouseInterfaceVO.class, item);
                            String realProperty =
                                    house.getQlrxxList().stream()
                                            .map(HouseInterfaceDetailVO::getBdcqzh)
                                            .collect(Collectors.joining(","));
                            QueryWrapper<EduHouseNursery> houseQueryWrapper = new QueryWrapper<>();
                            EduHouseNursery odlHouse = null;
                            if (ObjectUtils.isEmpty(house.getBdcdyh())) {
                                QueryWrapper<EduHouseDetailNursery> houseDetailQueryWrapper =
                                        new QueryWrapper<>();
                                houseDetailQueryWrapper
                                        .lambda()
                                        .eq(EduHouseDetailNursery::getYear, finalYear)
                                        .in(
                                                EduHouseDetailNursery::getRealProperty,
                                                house.getQlrxxList().stream()
                                                        .map(HouseInterfaceDetailVO::getBdcqzh)
                                                        .collect(Collectors.toList()))
                                        .in(
                                                EduHouseDetailNursery::getIdcard,
                                                house.getQlrxxList().stream()
                                                        .map(HouseInterfaceDetailVO::getZjh)
                                                        .collect(Collectors.toList()))
                                        .select(EduHouseDetailNursery::getHouseId);
                                List<String> idList =
                                        eduHouseDetailNurseryService
                                                .list(houseDetailQueryWrapper)
                                                .stream()
                                                .map(EduHouseDetailNursery::getHouseId)
                                                .distinct()
                                                .collect(Collectors.toList());
                                for (int i = 0; i < idList.size(); i++) {
                                    EduHouseNursery oldhouseById =
                                            eduHouseNurseryService.getById(idList.get(i));
                                    if (house.getZl().equals(oldhouseById.getAddress())) {
                                        odlHouse = oldhouseById;
                                    }
                                }
                            } else {
                                houseQueryWrapper
                                        .lambda()
                                        .eq(EduHouseNursery::getRealPropertyNum, house.getBdcdyh())
                                        .eq(EduHouseNursery::getRealProperty, realProperty)
                                        .eq(EduHouseNursery::getYear, finalYear);
                                odlHouse = eduHouseNurseryService.getOne(houseQueryWrapper);
                            }
                            EduHouseNursery eduHouse;
                            if (!ObjectUtils.isEmpty(odlHouse)) {
                                eduHouse = odlHouse;
                            } else {
                                eduHouse = new EduHouseNursery();
                                eduHouse.setHouseId(IdUtil.simpleUUID());
                            }
                            eduHouse.setAddress(house.getZl());
                            if (!ObjectUtils.isEmpty(house.getDjsj())) {
                                eduHouse.setRegisterDate(
                                        DateUtil.parse(house.getDjsj(), "yyyy年MM月dd日"));
                            }
                            if (!ObjectUtils.isEmpty(house.getQlrxxList())) {
                                eduHouse.setRealProperty(realProperty);
                            }
                            eduHouse.setRealPropertyNum(house.getBdcdyh());
                            if (!ObjectUtils.isEmpty(house.getTdsyqssj())) {
                                eduHouse.setBegDate(
                                        DateUtil.parse(house.getTdsyqssj(), "yyyy年MM月dd日"));
                            }
                            if (!ObjectUtils.isEmpty(house.getTdsyjssj())) {
                                eduHouse.setEndDate(
                                        DateUtil.parse(house.getTdsyjssj(), "yyyy年MM月dd日"));
                            }
                            String yt = house.getYt().replace("/", "").trim();
                            eduHouse.setLandCategories(
                                    saveDict(
                                            "LANDCATEGORIES", yt, vo.getAccessToken()));
                            eduHouse.setLandCategoriesName(yt);
                            eduHouse.setHouseNature(
                                    saveDict(
                                            "HOUSENATURE", house.getFwxz(), vo.getAccessToken()));
                            eduHouse.setHouseNatureName(house.getFwxz());
                            eduHouse.setYear(finalYear);
                            eduHouse.setStatus("1");
                            eduHouse.setAuthStatus(AuthStatusEnum.NODO.getType());
                            ArrayList<EduHouseDetailNursery> detailList = new ArrayList<>();
                            if (!ObjectUtils.isEmpty(house.getQlrxxList())) {
                                List<HouseInterfaceDetailVO> qlrxxList = house.getQlrxxList();
                                if (!ObjectUtils.isEmpty(house.getTdsyjssj())
                                        && !ObjectUtils.isEmpty(house.getTdsyqssj())) {
                                    int betweenYear =
                                            (int)
                                                    DateUtil.betweenYear(
                                                            DateUtil.offsetDay(
                                                                    DateUtil.parse(
                                                                            house.getTdsyqssj(),
                                                                            "yyyy年MM月dd日"),
                                                                    -1),
                                                            DateUtil.parse(
                                                                    house.getTdsyjssj(),
                                                                    "yyyy年MM月dd日"),
                                                            false);
                                    eduHouse.setYearLimit(betweenYear);
                                } else {
                                    eduHouse.setYearLimit(100);
                                }
                                if (!ObjectUtils.isEmpty(realProperty)
                                        && (realProperty.contains("证明")
                                        || realProperty.contains("预"))) {
                                    eduHouse.setAuthStatus(AuthStatusEnum.YES.getType());
                                    eduHouse.setStatus(BoolEnum.FALSE.getType());
                                }
                                house.getQlrxxList()
                                        .forEach(
                                                qlrxx -> {
                                                    QueryWrapper<EduHouseDetailNursery>
                                                            detailQueryWrapper =
                                                            new QueryWrapper<>();
                                                    detailQueryWrapper
                                                            .lambda()
                                                            .eq(
                                                                    EduHouseDetailNursery
                                                                            ::getRealProperty,
                                                                    qlrxx.getBdcqzh())
                                                            .eq(
                                                                    EduHouseDetailNursery
                                                                            ::getHouseId,
                                                                    eduHouse.getHouseId())
                                                            .eq(
                                                                    EduHouseDetailNursery
                                                                            ::getIdcard,
                                                                    qlrxx.getZjh())
                                                            .eq(
                                                                    EduHouseDetailNursery::getYear,
                                                                    finalYear);
                                                    EduHouseDetailNursery detail;
                                                    EduHouseDetailNursery odlHouseDetail =
                                                            eduHouseDetailNurseryService.getOne(
                                                                    detailQueryWrapper);
                                                    if (!ObjectUtils.isEmpty(odlHouseDetail)) {
                                                        detail = odlHouseDetail;
                                                    } else {
                                                        detail = new EduHouseDetailNursery();
                                                        detail.setHouseDetailId(
                                                                IdUtil.simpleUUID());
                                                    }
                                                    detail.setHouseId(eduHouse.getHouseId());
                                                    detail.setRealProperty(qlrxx.getBdcqzh());
                                                    detail.setIdcard(qlrxx.getZjh());
                                                    detail.setFullName(qlrxx.getQlr());
                                                    detail.setCommonSituation(
                                                            saveDict(
                                                                    "COMMONSITUATION",
                                                                    qlrxx.getGyfs(),
                                                                    vo.getAccessToken()));
                                                    detail.setCommonSituationName(qlrxx.getGyfs());
                                                    detail.setYear(eduHouse.getYear());
                                                    detail.setStatus("1");
                                                    detailList.add(detail);
                                                });
                            }
                            eduHouseNurseryService.saveOrUpdate(eduHouse);
                            eduHouseDetailNurseryService.saveOrUpdateBatch(detailList);
                            eduHouseVOList.add(Convert.convert(EduHouseVO.class, eduHouse));
                        });
            }
        } catch (Exception e) {
            logger.error("房产获取异常"+e.getMessage());
            throw new AppException(e.getMessage());
        }
        return eduHouseVOList;

    }


}
